Skip to content

Instantly share code, notes, and snippets.

@realeroberto
Created February 6, 2016 14:28
Show Gist options
  • Save realeroberto/95444a81efc0cf847734 to your computer and use it in GitHub Desktop.
Save realeroberto/95444a81efc0cf847734 to your computer and use it in GitHub Desktop.
A naive implementation of Insertion Sort in C.
/*
* a naive implementation of Insertion Sort in C.
*/
void
insertion_sort(int *array, int array_len)
{
int i;
for (i = 1; i < array_len; i++) {
int value = array[i];
int j = i - 1;
int done = 0;
for (;;) {
if (array[j] > value) {
array[j + 1] = array[j];
j--;
if (j < 0) {
done = 1;
}
} else {
done = 1;
}
if (done) break;
}
array[j + 1] = value;
}
}
/*
* let's try it...
*/
#include <stdio.h>
#include <stdlib.h>
int
main()
{
int array_len = 1000;
int array[array_len];
int i;
for (i = 0; i < array_len; i++) {
array[i] = random() / (RAND_MAX / 10000);
}
insertion_sort(array, array_len);
for (i = 0; i < array_len; i++) {
printf ("%d\n", array[i]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment