Bubble sort algorithm is comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order. This algorithm is not suitable for large data sets as its average and worst case complexity are of Ο(n2) where n is the number of items.
public class Sort {
public static void bubbleSort(int arr[]) {
int temp;
for(int i=0;i<arr.length-1;i++)
{
for (int j = 0; j < (arr.length - 1) - i; j++)
{
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp; }
}
}
}
public static void main(String[] strr) {
int arr[] = {23,67,90,12,3,87,34,23,78,56};
System.out.println(" Before sorting");
for(int j=0;j<=arr.length-1;j++)
{
System.out.print(" "+arr[j]);
}
bubbleSort(arr);
System.out.println("\nAfter Sorting");
for(int j=0;j<=arr.length-1;j++)
{
System.out.print(" "+arr[j]);
}
}
}
output:
Before sorting
23 67 90 12 3 87 34 23 78 56
After Sorting
3 12 23 23 34 56 67 78 87 90
Time Complexity:
The complexity of bubble sort is Ο(n2) in both worst and average cases, because the entire array needs to be iterated for every element.