static void Main(string[] args) { int[] datas = new int[100000]; Random r = new Random(); for (int i = 0; i < 100000; i++) { datas[i] = r.Next(1, 10000); } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); int[] newdatas = SortChoice(datas); stopwatch.Stop(); foreach (int data in newdatas) { Console.WriteLine(data); } Console.WriteLine("用时:" + stopwatch.ElapsedMilliseconds); Console.ReadKey(); } static int[] SortChoice(int[] datas) { int length = datas.Length; int[] newArr = new int[datas.Length]; for (int x = 0; x < length; x++) { newArr[x] = datas[x]; } int index = 0; for (int i = 0; i < length; i++) { index = i; for (int j = i + 1; j < length; j++) { if (newArr[j] < newArr[index]) { index = j; } } if (index != i) { int temp = newArr[i]; newArr[i] = newArr[index]; newArr[index] = temp; } } return newArr; }
原理其实跟冒泡排序是一样的,不同的是,选择排序减少了交换的次数,可以看出,代码中发现了更小的元素时,不是选择交换合适选择记录下来,最后的时候才判断需要需要交换再进行交换。
因为少了交换的步骤,效率会比冒泡排序的要快。
模拟排序10W条随机数据用时:16886ms