插入排序的實現思路
插入排序,在要排序的元素中,假定前n-1個數已經排好序,現在將第n個數插到前面的有序數列中,使得這n個數也是排好順序的。如此反覆循環,直到全部排好順序。
算法實現
void Insertionsort(int a[], int size)
{
//循環從第2個元素開始
int temp = 0;
for (int i = 1; i < size; i++)
{
if (a[i] < a[i - 1])
{
int j = i - 1;
temp = a[i];
for (; j >= 0 && a[j] > temp; j--)
{
a[j + 1] = a[j];
}
a[j + 1] = temp;
}
}
}
參考資料
https://www.toutiao.com/a6593273307280179715/?iid=6593273307280179715