Exemple de tri de sélection Java
Selection sort est un tri par comparaison sur place. 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. Explication
#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]
Voici l'implémentation du tri de sélection Java.
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. Exemple de tri de sélection Java
Un exemple complet pour illustrer l'utilisation de l'algorithme de tri de sélection pour trier un ensemble de données simple.
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 } } }
Sortie
[1, 5, 7, 8, 9, 10, 88, 99]