 Java Tutorial

Java Program for Bubble Sorting

What is bubble sort ?

Bubble sort is repeatedly comparing pairs of adjacent elements and then swapping their positions if they exist in the wrong order.

Bubble sorting can be used for collections of numbers, strings, characters etc.

The basic idea behind bubble sort is to imagine that the records to be sorted are kept in an array held vertically. The records with lower key values are 'light' and bubble up to the top. We make repeated iteration over the array from bottom to top.

Example, consider sorted collection of elements  Bubble Sort Time Complexity

Time complexity of bubble sort is O(n^2) in both worst and average cases, here complete array is iterated for each elements.

Bubble Sort Java Program

```import java.util.Scanner;

public class BubbleSortingTest {
public static void bubbleSort(int[] numberList){
int temp = 0;
for (int k=0;k<numberList.length-1;k++){
for(int i=0; i<(numberList.length-k-1);i++){
if (numberList[i] > numberList[i+1]){
// Swapping of positions if not in sorted order
temp = numberList[i];
numberList[i] = numberList[i+1];
numberList[i+1] = temp;
}
}
}
}
public static void main(String[] args){
int[] numberList;
Scanner in = new Scanner(System.in);
System.out.println("Enter numbers count: ");
int count = in.nextInt();
numberList = new int[count];
System.out.println("Enter numbers: ");
for (int i=0;i<count;i++){
numberList[i]=in.nextInt();
}
in.close();
bubbleSort(numberList);

System.out.println("Sorted numbers: ");
for(int number : numberList){
System.out.print(number+"\t");
}
}
}
```
Output:
```\$ javac BubbleSortingTest.java
\$ java BubbleSortingTest
Enter numbers count: 5
Enter numbers:
4
5
1
8
2
Sorted numbers:
1	2	4	5	8
```     