Skip to content

Instantly share code, notes, and snippets.

@taisyo7333
Created October 23, 2016 01:03
Show Gist options
  • Save taisyo7333/24692eec75755516af28b75dddef7007 to your computer and use it in GitHub Desktop.
Save taisyo7333/24692eec75755516af28b75dddef7007 to your computer and use it in GitHub Desktop.
Language C : Insert Sort
#include<stdio.h>
#include<stdlib.h>
#define DATA_NUM 10
void InsertSort(int data[], int data_num)
{
for (int pos = 1; pos < data_num; ++pos)
{
int ins_pos = pos;
while (ins_pos > 0 && data[ins_pos] < data[ins_pos - 1])
{
int tmp = data[ins_pos];
data[ins_pos] = data[ins_pos - 1];
data[ins_pos - 1] = tmp;
ins_pos--;
}
}
}
void ShowArray(int data[], int data_num)
{
printf("{ ");
for (int i = 0; i < data_num; i++)
{
printf(" %d,", data[i]);
}
printf(" }\n");
}
int main()
{
int data[DATA_NUM];
srand(100);
for (int i = 0; i < DATA_NUM; i++)
{
data[i] = rand() % 100;
}
ShowArray(data, DATA_NUM);
InsertSort(data, DATA_NUM);
ShowArray(data, DATA_NUM);
return 0;
}
{ 65, 16, 15, 4, 4, 54, 98, 2, 9, 29, }
{ 2, 4, 4, 9, 15, 16, 29, 54, 65, 98, }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment