每轮循环将该轮最小的数放在前面已排好的数的末尾
最好最坏平均复杂度是O(n*n)
Pseudocode:
selectionSort (arr)
{
Find the smallest card. Swap it with the first card.
Find the second-smallest card. Swap it with the second card.
Find the third-smallest card. Swap it with the third card.
Repeat finding the next-smallest card, and swapping it into the correct position until the array is sorted.
}
Java:
package ncku.cdc.sorting;
import java.util.Random;
public class SelectionSort {
private int[] sequence;
public SelectionSort(int size, int range) {
sequence = new int[size];
Random rand = new Random();
for (int i = 0; i < size; i++) {
sequence[i] = rand.nextInt(range);
}
}
public static void main(String[] args) {
int size = Integer.valueOf(args[0]);
int range = Integer.valueOf(args[1]);
SelectionSort selection = new SelectionSort(size, range);
System.out.println("before selectionSort:");
SortingTools.validation(selection.getSequence(), 0);
selection.selectionSort(selection.getSequence());
System.out.println("after selectionSort:");
SortingTools.validation(selection.getSequence(), 0);
}
public void selectionSort(int[] arr) {
int len = arr.length;
int i = 0;
int j;
int min;
while (i < len) {
min = i;
for (j = i + 1; j < len; j++) {
if (arr[j] < arr[min]) { min = j; }
}
swap(arr, i++, min);
}
}
private void swap(int[] arr, int i, int j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
public int[] getSequence() {
return sequence;
}
}
程序输入: 35 200. 表示生成长度为35, 数字范围从[0, 200)的数组
程序输出:
before selectionSort:
143 38 58 102 182 19 65 65 31 113 94 18 107 167 182 15 51 74 176 2 42 160 11 81 0 102 95 169 3 86 41 64 31 105 64
after selectionSort:
0 2 3 11 15 18 19 31 31 38 41 42 51 58 64 64 65 65 74 81 86 94 95 102 102 105 107 113 143 160 167 169 176 182 182