Skip to content

Instantly share code, notes, and snippets.

@ardrabczyk
Created September 14, 2015 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ardrabczyk/c616a646efe2b6605456 to your computer and use it in GitHub Desktop.
Save ardrabczyk/c616a646efe2b6605456 to your computer and use it in GitHub Desktop.
Insertion sort implementation in C
#include <stdio.h>
#include <stdlib.h>
void print(int arr[], size_t size)
{
unsigned i = 0;
for (; i < size; ++i)
{
printf("%d ", arr[i]);
}
printf("\n");
}
void insertion_sort(int arr[], size_t size)
{
unsigned int i = 1;
int j;
int curr;
for(; i < size; ++i)
{
j = i - 1;
curr = arr[i];
for (; j >= 0; j--)
{
if (curr < arr[j])
{
arr[j + 1] = arr[j];
}
else
{
break;
}
}
arr[j + 1] = curr;
}
}
int main(void)
{
int a[] = {5, 1, 4, 2, 0};
printf("Before sorting: \n");
print(a, sizeof a / sizeof (int));
insertion_sort(a, sizeof a / sizeof (int));
printf("Result: \n");
print(a, sizeof a / sizeof (int));
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment