排序演算法:選擇排序

ZealotZZZ發表於2019-03-04

Sorting Algorithms:Selection Sort

前言

該部落格用於本弱雞複習鞏固,打牢基礎,還望各大佬不吝賜教。

基本思路

遍歷陣列,把最小(大)的元素放在陣列首部,
把剩下的元素看做一個陣列,再次遍歷,
獲得最小(大)的元素放在陣列首部
意在每次遍歷新陣列選擇出最小(大)元素

動圖示例

Selection Sort
Selection Sort

演算法複雜度分析

平均 最壞 最好 穩定性 空間複雜度
O(n^2) O(n^2) O(n^2) 不穩定 O(1)

p.s. 最好情況:即不用元素交換,但仍要進行比較。比較次數n(n-1)/2次

程式碼實現

import java.util.Arrays;
import java.util.Random;

/**
 * Selection Sort
 * 遍歷陣列,把最小(大)的元素放在陣列首部,
 * 把剩下的元素看做一個陣列,再次遍歷,
 * 獲得最小(大)的元素放在陣列首部
 * 意在每次遍歷新陣列選擇出最小(大)元素
 * <p>
 * 演算法複雜度分析
 * 比較次數 n(n-1)/2 次
 * 時間複雜度(平均)   O(n^2) 外迴圈n次,內迴圈m次 m*n
 * 時間複雜度(最壞)   O(n^2) 外迴圈n次,內迴圈m次 m*n
 * 時間複雜度(最好)   O(n^2) 即不用元素交換,但仍要進行比較
 * 空間複雜度           O(1)
 * 穩定性             不穩定
 *
 * @author Wayne Zhang
 * @date 2018/07/14
 */

public class SelectionSort {

    public static void main(String[] args) {
        int[] a = new int[10];
        //random array
        for (int i = 0; i < a.length; i++) {
            Random rd = new Random();
            a[i] = rd.nextInt(10);
        }

        System.out.println("Random Array :");
        System.out.println(Arrays.toString(a));
        System.out.println();
        System.out.println("Selection Sort :");

        int temp = 0;
        //外迴圈規定遍歷次數,最後只剩一個元素則不需再遍歷
        //所以外迴圈遍歷 n-1次陣列
        for (int i = 0; i < a.length - 1; i++) {
            //當前遍歷陣列最小元素的角標,初始時令其=i
            int minIndex = i;
            //將剩餘未排序元素當成新的陣列,與該陣列首位元素比較
            //比較後記錄最小元素的角標
            for (int j = i + 1; j < a.length; j++) {
                //比較
                if (a[minIndex] > a[j]) {
                    minIndex = j;
                }
            }
            //根據最小元素的角標,將其放到當前陣列的首位
            if (minIndex != i) {
                temp = a[minIndex];
                a[minIndex] = a[i];
                a[i] = temp;
            }
        }

        System.out.println(Arrays.toString(a));

    }
}
複製程式碼

參考

GeekforGeeks: https://www.geeksforgeeks.org/selection-sort/

十大經典排序演算法:https://www.cnblogs.com/onepixel/articles/7674659.html

《大話資料結構》:https://book.douban.com/subject/6424904/

相關文章