Bubble Sort

... by Bittle in Sorting Algorithms December 30, 2018

Bubble Sort is one of the easiest sorts to implement, but is too slow for real world use. Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent pairs and swaps them if they are in the wrong order. This algorithm is named for the way smaller (or larger) numbers bubble to the front of the list. The algorithm runs as follows:

Before proceeding to the code try to implement the algorithm on your own.


Solution (in java):

import java.util.Arrays;

public class BubbleSort {
    static int[] bubbleSort(int[] arr) {
        int length = arr.length;
        int temp;
        for (int i = 0; i < length; i++) {
            for (int j = 1; j < (length - i); j++) {
                if (arr[j - 1] > arr[j]) { // change to < for descending order
                    //swap elements
                    temp = arr[j - 1];
                    arr[j - 1] = arr[j];
                    arr[j] = temp;
                }

            }
        }
        return arr;
    }

    public static void main(String[] args) {
        int arr[] = {2, 40, 2, 25, -5, 15, 20, 155};
        System.out.println(Arrays.toString(bubbleSort(arr)));

    }
}


Output:

[-5, 2, 2, 15, 20, 25, 40, 155]


Bubble sort keeps on running until no more swaps are made, and runs in O(n^2) runtime.

Comments (0)

Search Here