Javaの選択ソートの例

Java選択ソートの例

Selection sortは、インプレース比較ソートです。 It loops and find the first smallest value, swaps it with the first element; loop and find the second smallest value again, swaps it with the second element, repeats third, fourth, fifth smallest values and swaps it, until everything is in correct order.

P.S Selection sort is inefficient on large lists

1. 説明

#unsorted data -> [10, 8, 99, 7, 1, 5, 88, 9]

#1 -> [, 8, 99, 7, , 5, 88, 9] -> [, 8, 99, 7, , 5, 88, 9]
#2 -> [1, , 99, 7, 10, , 88, 9] -> [1, , 99, 7, 10, , 88, 9]
#3 -> [1, 5, , , 10, 8, 88, 9] -> [1, 5, , , 10, 8, 88, 9]
#4 -> [1, 5, 7, , 10, , 88, 9] -> [1, 5, 7, , 10, , 88, 9]
#5 -> [1, 5, 7, 8, , 99, 88, ] -> [1, 5, 7, 8, , 99, 88, ]
#6 -> [1, 5, 7, 8, 9, , 88, ] -> [1, 5, 7, 8, 9, , 88, ]
#7 -> [1, 5, 7, 8, 9, 10, , 99]  -> [1, 5, 7, 8, 9, 10, , 99]

#result : [1, 5, 7, 8, 9, 10, 88, 99]

これがJava Selectionソートの実装です。

    public static void sort(int[] input) {

        int inputLength = input.length;

        for (int i = 0; i < inputLength - 1; i++) {

            int min = i;

            // find the first, second, third, fourth... smallest value
            for (int j = i + 1; j < inputLength; j++) {
                if (input[j] < input[min]) {
                    min = j;
                }
            }

            // swaps the smallest value with the position 'i'
            int temp = input[i];
            input[i] = input[min];
            input[min] = temp;

            //next pls
        }

    }

2. Java選択ソートの例

選択ソートアルゴリズムを使用して単純なデータセットをソートする方法を示す完全な例。

SelectionSortExample.java

package com.example;

import java.util.Arrays;

public class SelectionSortExample {

    public static void main(String[] args) {

        int[] array = {10, 8, 99, 7, 1, 5, 88, 9};

        selection_sort(array);

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

    }

    private static void selection_sort(int[] input) {

        int inputLength = input.length;

        for (int i = 0; i < inputLength - 1; i++) {

            int min = i;

            // find the first, second, third, fourth... smallest value
            for (int j = i + 1; j < inputLength; j++) {
                if (input[j] < input[min]) {
                    min = j;
                }
            }

            // swaps the smallest value with the position 'i'
            int temp = input[i];
            input[i] = input[min];
            input[min] = temp;

            //next pls
        }

    }

}

出力

[1, 5, 7, 8, 9, 10, 88, 99]