Skip to content

Instantly share code, notes, and snippets.

@sojohnnysaid
Created June 22, 2018 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sojohnnysaid/2e1f28bce3a526db7c26b01026b76c82 to your computer and use it in GitHub Desktop.
Save sojohnnysaid/2e1f28bce3a526db7c26b01026b76c82 to your computer and use it in GitHub Desktop.
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