Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

經典排序演算法:選擇排序 Selection Sort 逐步拆解

顧名思義,選擇排序就是每一趟從未排序區間裡挑出最小(或最大)的數字,放到已排序區的末尾。比喻一下:對著一群數字喊「你們誰最小,出列站到最後邊」,反覆執行直到只剩一個。

以 [6 2 4 1 5 9] 示範每一趟的狀態

第一趟:找到最小值 1,與首位交換。

交換前:| 6 | 2 | 4 | 1 | 5 | 9 |
交換後:| 1 | 2 | 4 | 6 | 5 | 9 |

第二趟:在 [2 4 6 5 9] 中最小值為 2,本來就在首位,無需交換。

交換前:| 1 | 2 | 4 | 6 | 5 | 9 |
交換後:| 1 | 2 | 4 | 6 | 5 | 9 |

第三趟:剩餘 [4 6 5 9] 最小值為 4,同樣原位不動。

第四趟:從 [6 5 9] 找到 5,與 6 交換。

交換前:| 1 | 2 | 4 | 6 | 5 | 9 |
交換後:| 1 | 2 | 4 | 5 | 6 | 9 |

第五趟:剩 [6 9] 最小值 6 已在正確位置,不交換。排序完成,結果為 [1 2 4 5 6 9]。

一趟的內部細節

以第一趟為例:先把 6 暫定為最小值,然後依序與後面的每個數字比較,遇到更小的就「交換角色」——6 對 2 換成 2,2 對 4 不動,2 對 1 換成 1,1 對 5 不動,1 對 9 不動,走到尾端。最後把最小值 1 與首位交換,一趟結束。其餘各趟同理。

程式碼

static void selection_sort(int[] unsorted)
{
    for (int i = 0; i < unsorted.Length; i++)
    {
        int min = unsorted[i], min_index = i;
        for (int j = i; j < unsorted.Length; j++)
        {
            if (unsorted[j] < min)
            {
                min = unsorted[j];
                min_index = j;
            }
        }
        if (min_index != i)
        {
            int temp = unsorted[i];
            unsorted[i] = unsorted[min_index];
            unsorted[min_index] = temp;
        }
    }
}

static void Main(string[] args)
{
    int[] x = { 6, 2, 4, 1, 5, 9 };
    selection_sort(x);
    foreach (var item in x)
        Console.WriteLine(item);
    Console.ReadLine();
}

複雜度方面:時間一律 O(n²),比較次數固定為 n(n-1)/2;交換次數最多 n-1,這正是它相比氣泡排序的優勢。空間 O(1),且不穩定——因為長距離交換會打亂相同元素的相對次序。

Copyright © Linux教程網 All Rights Reserved