Bubble Sort

Code and Principle of Bubble Sort

Posted by Leonard Meng on November 8, 2014

Introduction

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst case time complexity is quite high.

How Bubble Sort Works?

bubble-sort

Consider an array int[] arr= {5, 1, 4, 2, 8}

  1. First Pass: Bubble sort starts with very first two elements, comparing them to check which one is greater.

    ( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.

    ( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4

    ( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2

    ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

  2. Second Pass: Now, during second iteration it should look like this:

    ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )

    ( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2

    ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

    ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

  3. Third Pass: Now, the array is already sorted, but our algorithm does not know if it is completed.The algorithm needs one whole pass without any swap to know it is sorted.

    ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

    ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

    ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

    ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

Bubble Sort in Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class BubbleSort {
    private static int[] bubbleSort(int[] arr){
        int size = arr.length;
        // Put biggest one to the right
        for(int i = 1; i < size; i++){
            for(int j = 0; j < size - i; j++){
                if(arr[j] > arr[j+1]){
                    int tmp = arr[j+1];
                    arr[j+1] = arr[j];
                    arr[j] = tmp;
                }
            }
        }
        return arr;
    }

    public static void main(String[] args) {
        int[] arr = {-1,0, 1, 9, 8, 7, 6, 5, 4, 3, 2, 0, -21, 32, 12, 4, 6, 8, 23,23};
        arr = bubbleSort(arr);
        for(int i = 0; i < arr.length; i++){
            System.out.println(arr[i]);
        }
    }
}

Complexity Analysis

  • Time Complexity: $O(n^2)$
  • Space Complexity: $O(1)$
Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Welcome to reprint, and please indicate the source: Lingjun Meng's Blog Keep the content of the article complete and the above statement information!