Bubble Sort Algorithm In Java:
Bubble sort algorithm is a one of the commonly used sorting technique in the data structure.According to the Bubble sort algorithm we can sort the data according to our requirement either ascending order or descending order.
In Bubble Sort algorithm we compare to indexes elements , If the previous index element is grater than next index element , So we can swap those elements and get the sorted elements list.
In Bubble Sort algorithm we compare to indexes elements , If the previous index element is grater than next index element , So we can swap those elements and get the sorted elements list.
Example: Let's discuss the Bubble Sort algorithm with the help of java program.
class BubbleSort
{
int n;
int[] arr;
public void getData()
{
System.out.println("Enter the size of array:");
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
arr=new int[n];
System.out.println("Enter the elements of array");
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
System.out.println("array element index"+(i+1));
}
System.out.println(" ");
System.out.println("Array elements before sorting:");
for(int i=0;i<n;i++)
{
System.out.print(arr[i]+" ");
}
}
public void logic()
{
for(int i=0;i<n;i++)
{
int temp=0;
for(int j=0;j<n-1-i;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
System.out.println("");
System.out.println("Array elements after sorting:");
for(int i=0;i<n;i++)
{
System.out.print(arr[i]+" ");
}
a
}
}
class Test
{
public static void main(String[] args)
{
BubbleSort b=new BubbleSort();
b.getData();
b.logic();
}
}
output
Enter the size of array:
5
Enter the elements of array
array element of index1
40
array element of index2
10
array element of index3
20
array element of index4
30
array element of index5
25
Array elements before sorting:
40 10 20 30 25
Array elements after sorting:
10 20 25 30 40