C#实现选择排序
源文件:http://pan.baidu.com/share/link?shareid=439747&uk=3912660076
参考代码来源于课本:
//Main
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SelectionSort { 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 SelectionSort { public class Function { /// <summary> /// 声明变量 /// </summary> 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); } public void Sort() { SelectionSort(); } /// <summary> /// 选择排序: /// 第一次迭代选择数组中的最小元素,将其与数组的第一个元素交换。 /// 第二次迭代选择数组中剩下元素的最小元素,将其与第二个元素交换。以此类推.... /// 最后,最大元素留在数组最后一个位置。 /// (第i次迭代之后,数组中最小的i个元素,已按升序放到了数组的前i个元素中) /// 核心算法时间复杂度: /// T(n)=O(n²) /// </summary> public void SelectionSort() { for (int index = 0; index < array.Length; index++) { //设最小元素索引为迭代的开始 int minValueIndex = index; //子循环开始索引 int subIndex = index; while (++subIndex < array.Length) { if (array[subIndex] < array[minValueIndex]) { //将最小值的索引更新 minValueIndex = subIndex; } } //将最小值提前 if (minValueIndex != index) Swap(index, minValueIndex); } } /// <summary> /// 元素交换 /// </summary> /// <param name="one"></param> /// <param name="another"></param> public void Swap(int one, int another) { int temp; temp = array[one]; array[one] = array[another]; array[another] = temp; } /// <summary> ///输出. /// </summary> /// <returns></returns> public override string ToString() { string temporary = string.Empty; foreach (int element in array) temporary += element + " "; return temporary += "\n"; } } }
//运行结果截图: