1. 程式人生 > 實用技巧 >C#資料結構與算法系列(二十):插入排序演演算法(InsertSort)

C#資料結構與算法系列(二十):插入排序演演算法(InsertSort)

1.介紹

插入排序演演算法屬於內部排序演演算法,是對於欲排序的元素以插入的方式找尋該元素的適當位置,以達到排序的目的

2.思想

插入排序(Insertion Sorting)的基本思想是:把n個待排序的元素看成為一個有序表和一個無序表,開始時有序表中只包含一個元素,

無序表中包含有n-1個元素,排序過程中每次從無序表中取出第一個元素,把它的排序碼依次與有序表元素的排序碼進行比較,將它插入到有序表中的適當位置,使之成為新的有序表。

3.思路圖

4.程式碼演示

using System;

namespace DataStructure
{
public class InsertSort
{
public static void Test()
{
int[] arr = { , , , }; Console.WriteLine($"排序的陣列:{ArrayToString(arr)}"); Console.WriteLine("\n封裝後的插入排序"); Sort(arr); Console.WriteLine("\n封裝前的插入排序"); arr = new int[] { , , , }; {
int insertValue = arr[]; int insertIndex = - ; while (insertIndex >= && insertValue < arr[insertIndex])
{
arr[insertIndex + ] = arr[insertIndex]; insertIndex--;
} if (insertIndex + != )
{
arr[insertIndex + ] = insertValue;
} Console.WriteLine($"\n第{1}輪排序後的結果:{ArrayToString(arr)}");
}
{
int insertValue = arr[]; int insertIndex = - ; while (insertIndex >= && insertValue < arr[insertIndex])
{
arr[insertIndex + ] = arr[insertIndex]; insertIndex--;
} if (insertIndex + != )
{
arr[insertIndex + ] = insertValue;
} Console.WriteLine($"\n第{2}輪排序後的結果:{ArrayToString(arr)}");
} {
int insertValue = arr[]; int insertIndex = - ; while (insertIndex >= && insertValue < arr[insertIndex])
{
arr[insertIndex + ] = arr[insertIndex]; insertIndex--;
} if (insertIndex + != )
{
arr[insertIndex + ] = insertValue;
} Console.WriteLine($"\n第{3}輪排序後的結果:{ArrayToString(arr)}");
}
} /// <summary>
/// 插入排序封裝
/// </summary>
/// <param name="arr"></param>
private static void Sort(int[] arr)
{
//要迴圈的次數
for (int i = ; i < arr.Length; i++)
{
//設定待插入的值
int insertValue = arr[i]; //設定待插入的索引
int insertIndex = i - ; //1.insertIndex >= 0保證在給insertValue找插入位置不越界
//2.insertValue < arr[insertIndex] 待插入的數,還沒有找到插入位置
//也就是說當待插入的值與前一個值比較,如果小於那麼就把值後移
while (insertIndex >= && insertValue < arr[insertIndex])
{
arr[insertIndex + ] = arr[insertIndex]; //一直與前一個比較,知道索引到0
insertIndex--;
} //當索引位置變了後,就說明插入位置找到
if (insertIndex + != i)
{ arr[insertIndex + ] = insertValue;
} Console.WriteLine($"\n第{i}輪排序後的結果:{ArrayToString(arr)}");
}
} /// <summary>
/// 將陣列轉換成String
/// </summary>
/// <param name="arr"></param>
/// <returns></returns>
public static string ArrayToString(int[] arr)
{ string result = ""; for (int i = ; i < arr.Length; i++)
{
result += arr[i] + ",";
} return result;
}
}
}

5.結果圖