In this tutorial you will learn about bubble sort in Java.
In bubble sort algorithm each element is compared with adjacent element and are swapped if not in correct order. It is one of the simplest but worst sorting algorithm. It is suitable for sorting small list of numbers.
As bubbles come up on surface in water, in the same way the lighter or smaller elements come forward and heavier or bigger elements goes back.
Below image shows how bubble sort algorithm works.
Time Complexity
Worst Case: O (n2)
Average Case: O (n2)
Best Case: O (n)
Program for Bubble Sort in Java
Here is a java program to sort an array using bubble sort.
package com; import java.util.Scanner; public class BubbleSortJava { public static void main(String args[]){ int i,j,n,a[],temp; Scanner sc = new Scanner(System.in); System.out.println("Enter size of array:"); n = sc.nextInt(); a = new int[n]; System.out.println("\nEnter elements of array:"); for(i=0;i<n;++i) a[i] = sc.nextInt(); //sorting array in ascending order for(i=0;i<n;++i){ for(j=0;j<(n-i-1);++j){ if(a[j]>a[j+1]){ //use < to sort in descending order temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } System.out.println("\nSorted array is:"); for(i=0;i<n;++i){ System.out.print(a[i]+" "); } } }
Output
Enter size of array:
5
Enter elements of array:
4 7 8 5 6
Sorted array is:
4 5 6 7 8