Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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