选择排序是就地比较排序。 它循环并找到第一个最小值,并与第一个元素交换; 循环并再次找到第二个最小值,将其与第二个元素交换,重复第三个,第四个,第五个最小值并交换,直到一切都按正确的顺序排列。
PS选择排序在大型列表上效率低下
1.解释
#unsorted data -> [10, 8, 99, 7, 1, 5, 88, 9] #1 -> [ 10 , 8, 99, 7, 1 , 5, 88, 9] -> [ 1 , 8, 99, 7, 10 , 5, 88, 9] #2 -> [1, 8 , 99, 7, 10, 5 , 88, 9] -> [1, 5 , 99, 7, 10, 8 , 88, 9] #3 -> [1, 5, 99 , 7 , 10, 8, 88, 9] -> [1, 5, 7 , 99 , 10, 8, 88, 9] #4 -> [1, 5, 7, 99 , 10, 8 , 88, 9] -> [1, 5, 7, 8 , 10, 99 , 88, 9] #5 -> [1, 5, 7, 8, 10 , 99, 88, 9 ] -> [1, 5, 7, 8, 9 , 99, 88, 10 ] #6 -> [1, 5, 7, 8, 9, 99 , 88, 10 ] -> [1, 5, 7, 8, 9, 10 , 88, 99 ] #7 -> [1, 5, 7, 8, 9, 10, 88 , 99] -> [1, 5, 7, 8, 9, 10, 88 , 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]