插入排序算法的思想是採用n-1趟循環,第一趟循環將第二個數插入到第一個數組成的子隊列中,
第二趟循環將第3個數插入到前2個已經排好序的子隊列中,
第i趟循環將第i+1個數插入到前i個已經排好序的子隊列中。。。。。。
源代碼如下:
void insert_sort(int a[],int n)
{
int index,inserter;
for(int i = 1;i<n;i++) //對於n-1次循環
{
inserter = a[i];
index = i-1;
while(index >=0&&a[index]>=inserter)
{
a[index+1] = a[index]; //將比較出來大的數向後移動
index--;
}
a[index] = inserter; //將要插入的數放入最終的位置
}
}