Пример сортировки Java Selection

Пример сортировки Java Selection

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 Selection

Полный пример, демонстрирующий использование алгоритма сортировки Selection для сортировки простого набора данных.

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]