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 @ 2010-02-11 12:47  jasen.kin  阅读(1268)  评论(0编辑  收藏  举报