I am just learning sorting (not for the first time). In bubble sort, we have the following as the code.
int bubble_sort(int *arr, size_t n) {
size_t i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return 0;
}
As you could all see, the inner loop has n-1 times (in for loop), which is understandable (a[i],a[i-1] is both involved in one iteration), but the outer loop have i < n, but it also works for i < n-1. But most implementation in internet have n as the outer loop value. Doing the outer loop n-1 works fine for worst case 5 4 3 2 1. Just wondering, if there is any set of inputs that will not work for n-1 times of outer loop . If there are please post it and explain. Thanks.
N-1 is fine as well. As you describe, the worst case requires N-1 swaps (as the last has to become the first and vise-versa). If you add a print of the i-variable to the inside of the if-statement, you’ll see that it’s never called in the last iteration. This means that the last iteration of the loop never results in any swapping.
An even more efficient implementation of Bubblesort does not use a for-loop as an outer loop, though. Have a look at the bit of code below. Can you see the execution difference?
By setting the flag only if actual swapping occured, you’ll end up jumping out of the loop much sooner when you’re in an average case.