Skip to content

Instantly share code, notes, and snippets.

@rcanepa
Last active August 29, 2015 14:15
Show Gist options
  • Save rcanepa/31a2e2e987c8b2c2f665 to your computer and use it in GitHub Desktop.
Save rcanepa/31a2e2e987c8b2c2f665 to your computer and use it in GitHub Desktop.
C++ Insertion Sort
#include <iostream>
#include <stdlib.h>
void insertion_sort(int *list, int lenght);
int main(int argc, char const *argv[])
{
int list_length = 30;
int list[list_length];
srand(time(NULL));
/* Generates a random int list */
for (int i = 0; i < list_length; i++)
{
list[i] = rand() % 300;
std::cout << i << ":" << list[i] << std::endl;
}
insertion_sort(list, list_length);
/* Check the result */
for (int k = 0; k < list_length; k++){
std::cout << list[k] << ",";
}
return 0;
}
void insertion_sort(int *list, int lenght)
{
int j;
int i_val;
for (int i = 1; i < lenght; i++)
{
j = i - 1;
i_val = list[i];
while (j >= 0 && (i_val < list[j]))
{
list[j + 1] = list[j];
j--;
}
list[j + 1] = i_val;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment