源文件:http://pan.baidu.com/share/link?shareid=439748&uk=3912660076
代码参考来源于课本:
//Main:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace InsertSort { class Program { static void Main(string[] args) { Console.WriteLine("Please enter the array length:"); int length = Convert.ToInt32(Console.ReadLine()); Function obj = new Function(length); Console.WriteLine("The array is:"); Console.WriteLine(obj); obj.Sort(); Console.WriteLine("Sorted array:"); Console.WriteLine(obj); Console.ReadKey(); } } }
//Class:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace InsertSort { class Function { private int[] array; private static Random ran = new Random(); /// <summary> /// 随机性初始化数组. /// </summary> /// <param name="length"></param> public Function(int length) { array = new int[length]; while (length > 0) array[--length] = ran.Next(0, 100); } /// <summary> /// ... /// </summary> public void Sort() { InsertionSort(array); } /// <summary> /// 插入排序: /// 算法第一次迭代时,取数组第二个元素,和第一个元素比较,排序。 /// 第二次迭代时取第三个元素,比较并插入相对于前两个元素的正确位置,此时,前三个元素排好序。 /// 依次.....迭代第i次时,原数组前i个元素排序.(但不一定处于最终位置,数组后面还有可能有更小的元素) /// 核心算法时间复杂度: /// T(n)=O(n²) /// </summary> /// <param name="array"></param> public void InsertionSort(int[] array) { //从第二个元素(向数组后遍历),然后从第三个,以此类推...... for (int index = 1; index < array.Length; index++) { //当前元素的副本(假定为比他前一个小的元素) int tempValue = array[index]; //当前元素位置的副本 int copyindex = index; //从当前位置向第一个元素遍历 while (copyindex > 0 && tempValue < array[copyindex - 1]) { //当当前的元素小于他的前一个元素时,将他的前一个元素的值赋值给当前元素(当前元素消失,但留的有副本) array[copyindex]=array[copyindex - 1] ; //从当前位置向后移动 copyindex--; } //最后得到了最开始的元素应该在的位置。覆盖原来这个位置元素的值。 array[copyindex] = tempValue; } } /// <summary> /// 输出. /// </summary> /// <returns></returns> public override string ToString() { string temporary = string.Empty; foreach (int element in array) temporary += element + " "; return temporary += "\n"; } } }
//运行结果截图: