My implementation of insertion sort in C
/* | |
Insertion sort algorithm in C by John James Yzaguirre. | |
Best case runtime is O(n) | |
Worst case runtime is O(n^2) | |
Given a list | |
If there are elements before current | |
Swap current with current-i | |
While current is less than current-i | |
decrement i until reaching first element | |
*/ | |
//-------------------------------------------------- | |
#include <stdio.h> | |
int main(void){ | |
int array[] = {6,5,4,3,2,1}; | |
int length = sizeof array/ sizeof array[0]; | |
for(int i = 1; i < length; i++){ | |
int j = i; | |
while(j >= 0 && array[j] < array[j-1]){ | |
int swap = array[j]; | |
array[j] = array[j-1]; | |
array[j-1] = swap; | |
j--; | |
} | |
} | |
for(int i = 0; i < length; i++) | |
printf("%i\n", array[i]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment