Skip to content

Instantly share code, notes, and snippets.

@pedrominicz
Created February 19, 2020 19:14
Show Gist options
  • Save pedrominicz/3097095ae867276845e9731712d9d7b5 to your computer and use it in GitHub Desktop.
Save pedrominicz/3097095ae867276845e9731712d9d7b5 to your computer and use it in GitHub Desktop.
Insert sort.
#include <stdio.h>
void insert_sort(int n, int array[]) {
for(int i = 1; i < n; ++i) {
int current = array[i];
int j = i;
while(j > 0 && array[j - 1] > current) {
array[j] = array[j - 1];
--j;
}
array[j] = current;
}
}
#define test(...) \
{ \
int array[] = { __VA_ARGS__ }; \
int size = sizeof(array) / sizeof(int); \
insert_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