Bubble Sort in Java

Below is an example of the Bubble Sort algorithm in Java. See the Bubble Sort page for more information and implementations.


bubble-sort in Java

public class BubbleSort {
    public static void main(String[] args)
    {
        int[] array = {12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8};
        BubbleSort sorter = new BubbleSort();
        sorter.bubbleSort(array);
        System.out.println(java.util.Arrays.toString(array));
    }

    void bubbleSort(int[] array)
    {
        int n = array.length;
        while (n > 0)
        {
            int lastModifiedIndex = 0;
            for (int currentIndex = 1; currentIndex < n; currentIndex++)
            {
                // if the item at the previous index is greater than the item at the `currentIndex`, swap them
                if (array[currentIndex - 1] > array[currentIndex])
                {
                    // swap
                    int temp = array[currentIndex - 1];
                    array[currentIndex - 1] = array[currentIndex];
                    array[currentIndex] = temp;
                    // save the index that was modified
                    lastModifiedIndex = currentIndex;
                }
            }
            // save the last modified index so we know not to iterate past it since all proceeding values are sorted
            n = lastModifiedIndex;
        }
    }
}

Discussion