Created
September 14, 2015 13:14
-
-
Save ardrabczyk/c616a646efe2b6605456 to your computer and use it in GitHub Desktop.
Insertion sort implementation in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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