Bubble Sorting in Java

Bubble sorting and Linear sorting are the easiest methods of sorting. Also they are the least optimized sorting algorithms. First we are going to look at bubble sorting in java.

In Bubble sort each element is compared with its next element, if the element is greater than the next element then they are swapped. This process starts by comparing 0th and 1st element and goes on till the end of array.

After the first cycle is completed we would have got the largest element at the end of array. Now in the second cycle, again we compare the 0th and 1st element and swap if needed. This comparison goes on just before the last element. Last element is not included because it is already sorted. After second cycle we got the second highest element at the end of array. Now this cycle continues until all elements are sorted.

Let us first look at the code and then at an example to understand more clearly.

public class Tech4Humans {
	public static void main(String[] args) {
		Integer[] arr = { 50, 90, 10, 5 };
		bubbleSorting(arr);
	}

	static void bubbleSorting(Integer[] arr) {
		System.out.print("Before sorting = ");
		for (int k = 0; k < arr.length; k++) {
			System.out.print(arr[k] + " ");
		}

		int temp, size = arr.length;

		// Bubble Sort loops starts here
		for (int i = 0; i < size; i++) {
			for (int j = 0; j < (size - i - 1); j++) {
				// swapping if element is greater than next element
				if (arr[j] > arr[j + 1]) {
					temp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = temp;
				}
			}
		}

		System.out.print("\nAfter Sorting = ");
		for (int k = 0; k < arr.length; k++) {
			System.out.print(arr[k] + " ");
		}
	}

}

Output

Before sorting = 50 90 10 5 
After Sorting = 5 10 50 90 

Explanation

Please note in the above example that i=0, i=1…. is considered cycle first, cycle second respectively. Whereas j=0, j=1, j=2… is used to handle the comparison and swapping of elements. In above example you can see after first cycle (i=0), we got the largest element(90) at end of array, so in second cycle(i=1) no comparison was made with last element(90). Similarly in third cycle no comparison was made with last 2 elements.

In the fourth cycle(i=3), last 3 elements are freezed, hence there is no sense of comparison of first element(0th) with itself, so inner j loop will not execute.

Complexity of Bubble Sort

Complexity of bubble sorting is О(n2).

Let us take a look at Selection Sorting.

Leave a Comment