Bubble Sort

bubble-sort

Overview

Bubble Sort is a simple brute force sorting algorithm. It works by comparing and swapping adjacent elements based on the sort condition. Bubble sort is implemented by using two loops and it can be enhanced by using a flag to exit the outer loop if there was no swapping in the inner loop. This algorithm is rarely ever used in real world scenarios as other algorithms such as Quick Sort, Merge Sort etc. provide way better performance.


Pseudocode

  • Compare two adjacent elements and swap if needed

Implementation

public class BubbleSortBlog {
    public static void main(String[] args) {
        int[] sampleArray = { 1, 5, 2, 7, 8, 9, 11, 3, 5 };

        bubbleSort(sampleArray);
        System.out.println(Arrays.toString(sampleArray));
       //Output: [1, 2, 3, 5, 5, 7, 8, 9, 11]
    }

    public static int[] bubbleSort(int[] array) {
        var isSwapped = false;
        for (int i = array.length - 1; i >= 0; i--) {
            for (int j = 0; j < i; j++) {
                if (array[j] > array[j+1]) {
                    var temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
                    isSwapped = true;
                }
            }
            if (!isSwapped)
                return array;
        }
        return array;
    }
}

Time Complexity

  • Worst case scenario – O(n2)
  • Best case scenario – O(n) when the list is already sorted

Subscribe to stackedList

Get the latest updates & blog posts right to your inbox

Articles you might like…