选择排序法的思想是,每次选择数组中最小的一位。实现起来只需要几行代码,时间复杂度是O(N^2)。
1 public static void SelectedSort(string[] datalist) 2 { 3 int minIndex; 4 for (int i = 0; i <= datalist.Length - 2; i++)//默认从小到大排序,遍历下标,若存在比当前基准下标小的,交换数据,再与下一位比较 5 { 6 minIndex = i; 7 for (int j = i + 1; j <= datalist.Length - 1; j++) 8 { 9 if (datalist[i].CompareTo(datalist[j]) > 0) 10 minIndex = j; 11 } 12 if (minIndex != i) 13 { 14 string temp = datalist[i]; 15 datalist[i] = datalist[minIndex]; 16 datalist[minIndex] = temp; 17 } 18 } 19 }
使用
1 string[] a = new string[] { "khlin", "hzluo", "jjguo", "hhchen", "jxhan", "lxiao", "jsxiao", "wwang", "lsxie", "lwang" }; 2 SelectedSort(a); 3 foreach(string stra in a) 4 Console.Write("{0}, ",stra); 5 Console.WriteLine();
结果