直接插入排序

直接插入排序的基本操作是將一個記錄插入到已經排好序的有序表中,從而得到一個新的、記錄數增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;
                }
            }
        }
    }
}

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容