Bubble sort

The problem

Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller elements "bubble" to the top of the list. Although the algorithm is simple, it is too slow and impractical for most problems even when compared to insertion sort.[1] It can be practical if the input is usually in sort order but may occasionally have some out-of-order elements nearly in position.

Write a sort method that uses the bubble sort algorithm. The bubble sort algorithm makes several passes through the array. On each pass, successive neighboring pairs are compared. If a pair is not in order, its values are swapped; otherwise, the values remain unchanged. The technique is called a bubble sort or sinking sort because the smaller values gradually “bubble” their way to the top and the larger values “sink” to the bottom. Write a test program that reads in ten double numbers, invokes the method, and displays the sorted numbers.

Breaking it down

private static final int SAMPLE_SIZE = 100;

public static void main(String[] args) {

    Random random = new Random(10);
    int[] numbers = random.ints(0, 1000).limit(SAMPLE_SIZE).toArray();

    bubbleSort(numbers);
    Arrays.stream(numbers).forEach(i -> System.out.println(i));
}

public static void bubbleSort(int[] numbers) {

    boolean change;
    do {
        change = false;
        for (int i = 0; i < numbers.length - 1; i++) {

            if (numbers[i] > numbers[i + 1]) {
                int temp = numbers[i];
                numbers[i] = numbers[i + 1];
                numbers[i + 1] = temp;
                change = true;
            }
        }

    } while (change);

}

Output

12
39
88
99
99
108
113
117
135
...
902
902
907
928
953
959
960
971
974
979
981