选择排序的原理是通过正向遍历找到最小的数字,然后交换到 "第一个" 位置来实现的。需要两个循环来完成,外部循环的作用是调整起始位置,内部循环则是在剩余数据中查找最小数字。
var array = new int[] { 2, 9, 5, 1, 8, 3, 6, 4, 7, 0 };
for (int outer = 0; outer < array.Length - 1; outer++) { var minIndex = outer; for (int inner = outer + 1; inner < array.Length; inner++) { if (array[inner] < array[minIndex]) minIndex = inner; }
var temp = array[outer]; array[outer] = array[minIndex]; array[minIndex] = temp;
var s = String.Join(",", Array.ConvertAll(array, i => i.ToString())); Console.WriteLine("O:{0}, A:[{1}]", outer, s); }
排序过程:
O:0, A:[0,9,5,1,8,3,6,4,7,2] O:1, A:[0,1,5,9,8,3,6,4,7,2] O:2, A:[0,1,2,9,8,3,6,4,7,5] O:3, A:[0,1,2,3,8,9,6,4,7,5] O:4, A:[0,1,2,3,4,9,6,8,7,5] O:5, A:[0,1,2,3,4,5,6,8,7,9] O:6, A:[0,1,2,3,4,5,6,8,7,9] O:7, A:[0,1,2,3,4,5,6,7,8,9] O:8, A:[0,1,2,3,4,5,6,7,8,9]