Java - 查找排序

 個人理解:
     每次找到當前查找數組的最小值,並替換位置

package com.example;

import java.util.Arrays;

public class SelectionSort {

    private static void sort(int [] array){
        System.out.println("遍歷前: " + Arrays.toString(array));
        for (int i = 0; i < array.length; i++) {
            // 因爲每一次循環, 都會把當前最小的值放在前面, 所以最小值的下標從循環下標開始
            int currentMinIndex = i;
            int currentMinNumber = array[i];
            System.out.println("判斷前, index = " + i + "\t currentMinNumber = " + currentMinNumber);
            // j = i + 1 是因爲當前最小的值已經是array[i]當前下標對應的值了, 所以要進行判斷的話只需要驗證後面的即可。
            for (int j = i + 1; j < array.length; j++) {
                // 當 當前最小值大於當前值時, 需要替換最小值與最小值目前下標
                if(currentMinNumber > array[j]){
                    currentMinNumber = array[j];
                    currentMinIndex = j;
                }
            }
            System.out.println("判斷後, index = " + currentMinIndex + "\t currentMinNumber = " + currentMinNumber);
            // 如果index值發生改變,說明存在比當前數值還小的值。
            // 先將找到的最小值的位置換成當前值, 然後將當前值的位置替換成當前最小值
            if(currentMinIndex != i){
                array[currentMinIndex] = array[i];
                array[i] = currentMinNumber;
            }
            System.out.println(Arrays.toString(array));
        }
        System.out.println("遍歷後: " + Arrays.toString(array));

    }

    public static void main(String[] args) {
        int [] array = {999, 55, 88, 99, 5, 8888, 57};
        sort(array);
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章