# 插入排序

排序毫无疑问是算法中最基本的问题，插入排序更是其中常用的一种类型。
插入排序的思路非常容易理解，就像打扑克牌时一张一张摸牌，然后把牌从小到大排列在手里。手里的牌总是排好序的，每摸一张牌，就从大到小去比较，直到找到合适的位置把摸到的牌放进去。用代码实现如下：

#include <stdio.h>
#include <stdlib.h>

#define SIZE_ARRAY_1 5
#define SIZE_ARRAY_2 6
#define SIZE_ARRAY_3 20

void insertion_sort(int a[], int n);
void showArray(int a[], int n);

void main()
{
int array1[SIZE_ARRAY_1]={1,4,2,-9,0};
int array2[SIZE_ARRAY_2]={10,5,2,1,9,2};
int array3[SIZE_ARRAY_3];

for(int i=0; i<SIZE_ARRAY_3; i++)
{
array3[i] = (int)((40.0*rand())/(RAND_MAX+1.0)-20);
}

printf("Before sort, ");
showArray(array1, SIZE_ARRAY_1);
insertion_sort(array1, SIZE_ARRAY_1);
printf("After sort, ");
showArray(array1, SIZE_ARRAY_1);

printf("Before sort, ");
showArray(array2, SIZE_ARRAY_2);
insertion_sort(array2, SIZE_ARRAY_2);
printf("After sort, ");
showArray(array2, SIZE_ARRAY_2);

printf("Before sort, ");
showArray(array3, SIZE_ARRAY_3);
insertion_sort(array3, SIZE_ARRAY_3);
printf("After sort, ");
showArray(array3, SIZE_ARRAY_3);
}

void showArray(int a[], int n)
{
if(n>0)
printf("This array has %d items: ", n);
else
printf("Error: array size should bigger than zero.\n");

for(int i=0; i<n; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}

/* insertion_sort
* Principle: Divide array into two parts: sorted part and unsorted
* part, insert the first item of unsorted part into sorted part.
*/
void insertion_sort(int a[], int n)
{
if(n<=0)
return;

for(int j=1;j<n;j++) {
int key = a[j];
// insert a[j] into sorted parts
int i = j-1;
while( i>=0 && a[i]>key ) {
a[i+1] = a[i];
i--;
}
a[i+1] = key;
}
}

04-13 2513

03-08 793

01-31 264

01-19 413

04-17 347

09-18 1346

08-17 2345

09-28 1632

04-28 1.8万

03-25 482