Javaの選択ソートの例
https://en.wikipedia.org/wiki/Sorting
algorithm#Selection
sort[選択ソート]は、インプレース比較ソートです。ループして最初の最小値を見つけ、最初の要素と交換します。 2番目に小さな値を見つけ出し、2番目の要素と交換し、3番目、4番目、5番目に小さい値を繰り返し、すべてが正しい順序になるまでスワップします。
P.S大きなソートリストでは選択ソートが効率的ではない
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.mkyong;
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].... === 参考文献 . https://www.cs.cmu.edu/~adamchik/15-121/lectures/Sorting%20Algorithms/sorting.html[Different 並べ替えの種類]。 https://en.wikipedia.org/wiki/Sorting__algorithm#Selection__sort%20target=[Wikipedia ソートアルゴリズム - 選択ソート] link://tag/algorithm/[algorithm]link://タグ/selection-sort/[selection ソート]リンク://タグ/ソート/[並べ替え]