Search code examples
for-loopbubble-sort

Could someone explain the logic behind the for loops in bubble sort?


So I understand the gist of bubble sort, switching pairs if they're not in the correct order, but what I don't get is the logic behind the limits in the for loops (i.e. i<array.length; and j<array.length-1. Could someone please explain why they are written that way???

int temp = 0;

for (int i = 0; i < data.length; i++) {
    for (int j = 1; j < (data.length - i); j++) {
        if (data[j - 1] > data[j]) {
            temp = data[j - 1];
            data[j - 1] = data[j];
            data[j] = temp;
        }
    }
}

Solution

  • It is not at all obvious at first sight but you should note that:

    Each time the outer loop completes another element will have "bubbled" its way to the top of the array.

    The top part of the array contains the highest elements - this top part grows. Starting with:

    3 1 4 1 5 9 2 6 5 4

    After one outer loop 9 has bubbled to the top

    1 3 1 4 5 2 6 5 4 9

    After the second run 6 has bubbled to the top

    1 1 3 4 2 5 5 4 6 9

    Each time the outer loop runs the inner loop can finish a little bit earlier as we know that the top part of the array will be sorted.