直接插入排序的基本操作是將一個記錄插入到已經排好序的有序表中,從而得到一個新的、記錄數增1的有序表。
插入排序基本原理
using System;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int[] sqList = new int[] { 0, 5, 4, 3 };
InsertSort(sqList);
sqList.ToList().ForEach(s => Console.Write(s + " "));
Console.ReadLine();
}
static void InsertSort(int[] sqList)
{
for (int i = 1; i < sqList.Length; i++) //假設第一個元素已經放好位置,后面的元素就是放在其左側或者右側
{
if (sqList[i] < sqList[i - 1])
{
int sentry = sqList[i]; //將即將排序的元素暫存,這里沒有將數組第一個元素設置為哨兵
int j;
for (j = i - 1; j >= 0 && sqList[j] > sentry; j--)
{
sqList[j + 1] = sqList[j];
}
sqList[j + 1] = sentry;
}
}
}
}
}