In my boredom today I decided to see if I could improve on a basic bubble sort without (knowingly) copying prior work. I know there have been many attempts to do so, and my approach seems closest to the cocktail shaker sort, but that doesn't seem to quite match.
In the below code it scans forward, but as soon as a swap is necessitated, it scans backwards until it finds a sorted pair, then picks up where it left off to scanning forward.
Consider sorting an input array [1 4 2 0 8]:
- [1 4] is sorted. No swap needed.
- [4 2] is not sorted. Swap to [2 4]. Begin scanning backward.
- [1 2] is sorted. Continue forward.
- [4 0] is not sorted. Swap to [0 4]. Begin scanning backward.
- [2 0] is not sorted. Swap to [0 2].
- [1 0] is not sorted. Swap to [0 1]. Reach beginning of array. Continue forward.
- [4 8] is sorted. No swap needed.
- End of array.
1 4 2 0 8
1 4 2 0 8
1 2 4 0 8
1 2 0 4 8
1 0 2 4 8
0 1 2 4 8
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void sort(int *arr, size_t n) {
for (size_t i = 0; i < n - 1; i++) {
if (arr[i] > arr[i+1]) {
swap(&arr[i], &arr[i+1]);
for (size_t j = i; j > 0 && arr[j-1] > arr[j]; j--) {
swap(&arr[j-1], &arr[j]);
}
}
}
}
Have I unwittingly copied something that didn't come up in my research, and if so, does it have a name?