Created
June 22, 2018 00:38
-
-
Save sojohnnysaid/2e1f28bce3a526db7c26b01026b76c82 to your computer and use it in GitHub Desktop.
My implementation of insertion sort 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
/* | |
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