【排序算法】選擇排序--Java實現

1、基本思想

選擇排序是一種簡單直觀的排序算法,其基本原理如下:對於給定的一組記錄,經過第一輪比較後得到最小的記錄,然後將該記錄的位置與第一個記錄的位置交換;接着對不包括第一個記錄以外的其他記錄進行第二次比較,得到最小記錄並與第二個位置記錄交換;重複該過程,直到進行比較的記錄只剩下一個爲止。

2、複雜度分析

從簡單選擇排序的過程來看,它最大的特點是交換移動數據次數相當少,這樣就節約了相應的時間。分析它的時間複雜度發現,無論是最好最差情況,其比較次數都是一樣多,第 i 趟排序需要進行 n-i 次關鍵字比較,此時需要比較這裏寫圖片描述次,對於交換次數而言,當最好的時候,交換0次,最差的時候,也就是初始降時,交換次數爲 n-1 次,基於最終的時間排序與交換次數總和,因此,總的時間複雜度依然爲這裏寫圖片描述。儘管與冒泡排序同爲這裏寫圖片描述,但簡單選擇排序的性能要優於冒泡排序。

3、選擇排序示意圖

這裏寫圖片描述

4、Java代碼如下

import java.util.Arrays;

public class SelectionSort {

    /**
     * 將最小的元素放在數組最前面
     * @param a
     * 
     */
    public static void selectSort(int[] a) {

        for (int i = 0; i < a.length; i++) {
            int temp = a[i];
            // 將當前下標定義爲最小值下標
            int flag = i; 
            for (int j = i + 1; j < a.length; j++) {

                // a[j] < temp 從小到大排序;a[j] > temp 從大到小排序
                if (a[j] < temp) {
                    temp = a[j];
                // 如果有小於當前最小值的關鍵字將此關鍵字的下標賦值給flag
                    flag = j; 
                }
            }
            //下標發生變化,元素互換
            if (flag != i) {
                a[flag] = a[i];
                a[i] = temp;
            }
        }
    }

    /**
     * 將數組中最大的元素放在數組末尾 
     * @param list
     *
     */
    public static void selectionSort(int[] list){

        for(int i = list.length - 1;i >= 1;i--){

            //每一趟進行比較時,默認的初始化值
            int currentMax = list[0];
            int currentMaxIndex = 0;

            // 選取數組元素最大值以及元素最大值下標
            for(int j = 1;j <= i;j++){
                if(currentMax < list[j]){
                    currentMax = list[j];
                    currentMaxIndex = j;
                }
            }

            // 當前最大值下標發生改變,最大值與最後一個元素互換
            if(currentMaxIndex != i){
                list[currentMaxIndex] = list[i];
                list[i] = currentMax;
            }
        }
    }

    public static void main(String[] args) {

        int[] sorta={4,7,2,9,6,3};
        int[] sortb={8,7,16,83,26,10,56};
        System.out.println("數組sorta排序前的結果:");
        for(int a:sorta){
            System.out.print(a+" ");
        }
        System.out.println();

        System.out.println("數組sortb排序前的結果:");
        for(int a:sortb){
            System.out.print(a+" ");
        }
        System.out.println();

        selectSort(sorta);
        System.out.println("數組sorta排序後的結果:");
        System.out.println(Arrays.toString(sorta));

        selectionSort(sortb);
        System.out.println("數組sortb排序後的結果:");
        System.out.println(Arrays.toString(sortb));
    }

}

代碼運行結果如下:

數組sorta排序前的結果:
4 7 2 9 6 3 
數組sortb排序前的結果:
8 7 16 83 26 10 56 
數組sorta排序後的結果:
[2, 3, 4, 6, 7, 9]
數組sortb排序後的結果:
[7, 8, 10, 16, 26, 56, 83]
發佈了101 篇原創文章 · 獲贊 139 · 訪問量 34萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章