選擇排序定義:每一趟從待排序的數據元素中選出最小(或最大)的一個元素,順序放在已排好序的數列的最后,直到全部待排序的數據元素排完。選擇排序是不穩定的排序方法。
class PRogram{ static void Main(string[] args) { int[] array = new[] { 234, 632, 23, 643, 2, 6, -2, 423, 2342,43 }; Console.WriteLine("排序前:"); Console.WriteLine(string.Join(",", array)); SelectSort(array); Console.WriteLine("排序后:"); Console.WriteLine(string.Join(",", array)); Console.ReadKey(); } /// <summary> /// 選擇排序 /// </summary> /// <param name="sources">目標數組</param> private static void SelectSort(int[] sources) { for (int i = 0, len = sources.Length - 1; i <= len; i++) { // 假設最小值索引 int minIndex = i; // 循環遍歷一遍找到最小值的索引 for (int j = i + 1; j <= len; j++) { // 如果最小值比其他元素大,重新設置最小值的索引 if (sources[minIndex] > sources[j]) { minIndex = j; } } // 臨時變量交換最小值的位置; int temp = sources[i]; sources[i] = sources[minIndex]; sources[minIndex] = temp; } }}
新聞熱點
疑難解答