Bubble Sort is basic sorting algorithm in programming languages.
In Bubble Sort algorithm, two adjacent elements are compared if elements are not in ascending order then swapping is done.
As you can see in the below pic, if two adjacent elements are not in ascending order then swapping is done as shown by arrows.
For one full comparison of elements there will be passes.(refer image).
In Bubble Sort algorithm, two adjacent elements are compared if elements are not in ascending order then swapping is done.
As you can see in the below pic, if two adjacent elements are not in ascending order then swapping is done as shown by arrows.
For one full comparison of elements there will be passes.(refer image).
ADVERTISEMENT
public class BubbleSort {
//implementation of bubble sort algorithm v1
//time complexity is O(n^2)
public static void main(String args[])
{
int arr[]={15,23,22,10,34,0,1};
int n = arr.length;
BubbleSort bs = new BubbleSort();
bs.bubbleSort(arr,n);
System.out.println("Sorted Array:");
bs.printArray(arr,n);
}
void bubbleSort(int arr[],int n)
{
//sorting algo logic
n=arr.length;
for(int i=0; i<n-1; i++) //for passes
{
for (int j=0; j<n-1-i; j++) //for element comparisons
{
if(arr[j]>arr[j+1])
{
//swapping will be done
int temp;
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
void printArray(int arr[],int n)
{
n = arr.length;
for(int i=0; i<n; i++)
{
System.out.print(arr[i]+" ");
}
}
}
Output:
Sorted Array:
0 1 10 15 22 23 34
Process finished with exit code 0
0 1 10 15 22 23 34
Process finished with exit code 0