Skip to content

Instantly share code, notes, and snippets.

@pedrominicz
Created February 19, 2020 19:15
Show Gist options
  • Save pedrominicz/c5a9ce49045ebb6136800b29c9c90614 to your computer and use it in GitHub Desktop.
Save pedrominicz/c5a9ce49045ebb6136800b29c9c90614 to your computer and use it in GitHub Desktop.
Shell sort.
#include <stdio.h>
void shell_sort(int n, int array[]) {
for(int gap = n / 2; gap > 0; gap /= 2) {
for(int i = gap; i < n; ++i) {
int temp = array[i];
int j = i;
while(j >= gap && array[j - gap] > temp) {
array[j] = array[j - gap];
j -= gap;
}
array[j] = temp;
}
}
}
#define test(...) \
{ \
int array[] = { __VA_ARGS__ }; \
int size = sizeof(array) / sizeof(int); \
shell_sort(size, array); \
for(int i = 0; i < size; ++i) { \
printf("%d ", array[i]); \
} \
printf("\n"); \
}
int main(void) {
test(1, 2, 6, 9, 8, 3, 10, 7, 5, 4);
test(7, 10, 2, 9, 1, 8, 5, 4, 6, 3);
test(5, 10, 3, 8, 6, 4, 7, 1, 9, 2);
test(3, 8, 10, 1, 9, 5, 7, 6, 2, 4);
test(2, 1, 8, 5, 4, 10, 7, 6, 9, 3);
test(6, 8, 3, 9, 5, 7, 2, 1, 10, 4);
test(1, 2, 6, 5, 9, 4, 8, 3, 7, 10);
test(1, 2, 8, 6, 5, 7, 10, 4, 3, 9);
test(3, 5, 4, 6, 8, 2, 10, 9, 7, 1);
test(9, 4, 3, 6, 1, 7, 2, 10, 8, 5);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment