Skip to content

Instantly share code, notes, and snippets.

@rszewczyk
Created December 5, 2017 23:19
Show Gist options
  • Save rszewczyk/b0e665a24df3da1c5ba6ae294394130d to your computer and use it in GitHub Desktop.
Save rszewczyk/b0e665a24df3da1c5ba6ae294394130d to your computer and use it in GitHub Desktop.
CMSC 104 - insertion sort
#include <stdio.h>
void printIntegerArray(int array[], int size)
{
int currentIndex = 0;
while (currentIndex < size)
{
printf("%d\n", array[currentIndex]);
currentIndex = currentIndex + 1;
}
printf("\n");
}
int main()
{
int numbers[10] = {6, 3, 1, 0, 7, 8, 21, 11, 3, 8};
printf("Before sort:\n");
printIntegerArray(numbers, 10);
// we start sorting at the second element since there is nowhere to
// move the first element
int i = 1;
// we process each element in the array, so we set our conditional
// to stop at the end of the array.
while (i < 10)
{
// assign the element at the current index to a temporary variable
int temp = numbers[i];
// starting at the the current index...
int j = i;
// ...compare each element to the temporary value
// stopping when we reach a number that is less than the temporary value
// or the begining of the array
while (j > 0 && numbers[j - 1] > temp)
{
// as we move to the left in the array, shift elements to the right
numbers[j] = numbers[j - 1];
j = j - 1;
}
// place the current element in the spot where we stopped the leftward search
numbers[j] = temp;
i = i + 1;
}
printf("After sort:\n");
printIntegerArray(numbers, 10);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment