- 直接插入排序,也叫插入排序冻晤,是9種經(jīng)典排序方法中最簡單的。
- 原理:以升序?yàn)槔?/strong>绸吸,在數(shù)組中依次往后選擇鼻弧,將要插入的數(shù)據(jù)插入到已經(jīng)排列好的數(shù)列中。
- 思路:在數(shù)組中锦茁,選取數(shù)組中第2個(gè)數(shù)據(jù)與第1個(gè)數(shù)據(jù)比較攘轩,如果比第1個(gè)數(shù)據(jù)小,則將第2個(gè)數(shù)據(jù)插入到底1個(gè)數(shù)據(jù)的前面码俩,而將原來的第1個(gè)數(shù)據(jù)移到數(shù)組的第2個(gè)位置度帮,以此類推。
以數(shù)組[6,5,4,3,2,1]為例:
第1次:5,6,4,3,2,1 選取數(shù)組中第2個(gè)數(shù)據(jù)“5”稿存,插入到前面的隊(duì)列中笨篷;
第2次:4,5,6,3,2,1 選取數(shù)組中第3個(gè)數(shù)據(jù)“4”甫菠,插入到前面的隊(duì)列中;
第3次:3,4,5,6,2,1 選取數(shù)組中第4個(gè)數(shù)據(jù)“3”冕屯,插入到前面的隊(duì)列中;
第4次:2,3,4,5,6,1 選取數(shù)組中第5個(gè)數(shù)據(jù)“2”拂苹,插入到前面的隊(duì)列中安聘;
第5次:1,2,3,4,5,6 選取數(shù)組中第6個(gè)數(shù)據(jù)“1”,插入到前面的隊(duì)列中瓢棒;
4.舉例:
(1)要排序的數(shù)組是:[15, 22, 35, 9, 16, 33, 15, 23, 68, 1, 33, 25, 14]浴韭。
//直接插入排序是9種經(jīng)典排序算法中最簡單的
static void Main(string[] args)
{
int[] array = { 15, 22, 35, 9, 16, 33, 15, 23, 68, 1, 33, 25, 14 }; //待排序數(shù)組
InsertSort(array,array.Length);
//控制臺(tái)遍歷輸出
Console.WriteLine("排序后的數(shù)列:");
foreach (int item in array)
Console.Write(item + " ");
Console.ReadLine();
}
static void InsertSort(int[] array,int length)
{
for(int i = 1;i< length;i++)
{
int temp = array[i]; //每次先記錄下來將要插入的值
for (int j=0;j<=i;j++)
{
if(array[j]> temp) //在插入過程中找到排序數(shù)組中比它大的數(shù)據(jù)
{
for(int k=i;k>j;k--)
{
array[k] = array[k - 1]; //找到之后,先保存數(shù)列好后面已經(jīng)排列好的數(shù)組脯宿,排序的數(shù)組后移騰出一個(gè)位置
}
array[j] = temp; //將插入值放在第1個(gè)比它大的數(shù)值位置
j = i; //最后念颈,可以將 j=i 結(jié)束本次循環(huán)
}
}
Console.WriteLine("第{0}次:",i);
foreach (int item in array)
Console.Write(item + " ");
Console.WriteLine();
}
}
5.輸出結(jié)果
第1次:
15 22 35 9 16 33 15 23 68 1 33 25 14
第2次:
15 22 35 9 16 33 15 23 68 1 33 25 14
第3次:
9 15 22 35 16 33 15 23 68 1 33 25 14
第4次:
9 15 16 22 35 33 15 23 68 1 33 25 14
第5次:
9 15 16 22 33 35 15 23 68 1 33 25 14
第6次:
9 15 15 16 22 33 35 23 68 1 33 25 14
第7次:
9 15 15 16 22 23 33 35 68 1 33 25 14
第8次:
9 15 15 16 22 23 33 35 68 1 33 25 14
第9次:
1 9 15 15 16 22 23 33 35 68 33 25 14
第10次:
1 9 15 15 16 22 23 33 33 35 68 25 14
第11次:
1 9 15 15 16 22 23 25 33 33 35 68 14
第12次:
1 9 14 15 15 16 22 23 25 33 33 35 68
排序后的數(shù)列:
1 9 14 15 15 16 22 23 25 33 33 35 68