C#插入排序

算法描述

  一般来说,插入排序都采用in-place在数组上实现。具体算法描述如下:

  1. 从第一个元素开始,该元素可以认为已经被排序

  2. 取出下一个元素,在已经排序的元素序列中从后向前扫描

  3. 如果该元素(已排序)大于新元素,将该元素移到下一位置

  4. 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置

  5. 将新元素插入到该位置中

  6. 重复步骤2

代码如下:如有BUG请及时回复,谢谢

复制代码
代码
 1 using System.Text;
 2 
 3 protected void Page_Load(object sender, EventArgs e)
 4     {
 5        InsertSort();
 6     }
 7 
 8 private void InsertSort()
 9     {
10         int[] inputIntArray = new int[8] { 8,7,6,5,4,3,2,1};
11         for (int i = 1; i < inputIntArray.Length; i++)
12         {   
13             //foreach the int array  :index of array is 0-7
14             if (inputIntArray[i] < inputIntArray[i - 1])
15             { //if  the last one is bigger than  the privious 
16                 int temp=inputIntArray[i];//stored the number of the last one 
17                 int j = 0;
18                 for (j = i - 1; j >= 0&&temp<inputIntArray[j]; j--)
19                 {//foreach the last to the first and  modify  that  the index of  j >= 0  and  inputIntArray[max]<inputIntArray[j]
20                    inputIntArray[j+1]=inputIntArray[j];
21                 }
22                 inputIntArray[j + 1= temp;//替换值
23             }
24             PrintSortedResult(inputIntArray,i);
25         }
26         //
27     }
28 
29  private void PrintSortedResult(int[] inputIntArray,int num)
30     {//打印操作结果
31         StringBuilder sb = new StringBuilder();
32         for (int i = 0; i < inputIntArray.Length; i++)
33         {
34             if (i == 0)
35             {
36                 sb.Append(inputIntArray[i].ToString());
37             }
38             else
39             {
40                 sb.Append("," + inputIntArray[i].ToString());
41             }
42         }
43         Response.Write(""+num+"次排序的结果:  "+sb.ToString()+"<br/>");
44     }
复制代码

 

 操作结果显示如下:

 

posted @   jasen.kin  阅读(1270)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示