1. 程式人生 > 實用技巧 >排序演算法-選擇排序

排序演算法-選擇排序

選擇排序是也是一種簡單粗暴的排序演算法。實現原理是一直找無序序列中的最小值(或者最大值)與待排序下標進行交換。

1.程式碼實現

以java實現為例:

public class SelectionSort {
    public static int[] selectionSort(int[] nums) {
        //迴圈遍歷序列的每一個下標
        for (int i = 0; i < nums.length; i++) {
            int minIndex = i; //記錄當前無序序列最小元素下標
            for (int j = i; j < nums.length; j++) {
                
if(nums[minIndex] > nums[j]){ minIndex = j; } } //如果最小元素下標不是待排序下標,就將兩個元素交換,把當前最小元素放到當前排序下標中 if(minIndex!=i){ int temp = nums[minIndex]; nums[minIndex] = nums[i]; nums[i] = temp; } }
return nums; } public static void main(String[] args) { int[] nums = new int[] { 9, 8, 7, 6, 5, 4, 3, 2, 10 }; int[] newNums = selectionSort(nums); for (int x : newNums) { System.out.print(x+" "); } } }

2.資料執行解析

資料的分解示例如下

[9 8 7 6 5 4 3 2 10]    每次拿到最小元素與待排序下標交換
->[2 8 7 6 5 4 3 9 10] ->[2 3 7 6 5 4 8 9 10] ->[2 3 4 6 5 7 8 9 10] ....

3.複雜度分析

選擇排序在最好最差和平均時間複雜度都是O(n²),空間複雜度為T(1)。