1 import java.util.Random;
2
3 public class SelectionSort {
4
5 public void selectionSort(int[] list) {
6 // 需要遍历获得最小值的次数
7 // 要注意一点,当要排序 N 个数,已经经过 N-1 次遍历后,已经是有序数列
8 for (int i = 0; i < list.length - 1; i++) {
9 int temp = 0;
10 int index = i; // 用来保存最小值得索引
11
12 // 寻找第i个小的数值
13 for (int j = i + 1; j < list.length; j++) {
14 if (list[index] > list[j]) {
15 index = j;
16 }
17 }
18
19 // 将找到的第i个小的数值放在第i个位置上
20 temp = list[index];
21 list[index] = list[i];
22 list[i] = temp;
23
24 System.out.format("第 %d 趟:\t", i + 1);
25 printAll(list);
26 }
27 }
28
29 // 打印完整序列
30 public void printAll(int[] list) {
31 for (int value : list) {
32 System.out.print(value + "\t");
33 }
34 System.out.println();
35 }
36
37 public static void main(String[] args) {
38 // 初始化一个随机序列
39 final int MAX_SIZE = 10;
40 int[] array = new int[MAX_SIZE];
41 Random random = new Random();
42 for (int i = 0; i < MAX_SIZE; i++) {
43 array[i] = random.nextInt(MAX_SIZE);
44 }
45
46 // 调用冒泡排序方法
47 SelectionSort selection = new SelectionSort();
48 System.out.print("排序前:\t");
49 selection.printAll(array);
50 selection.selectionSort(array);
51 System.out.print("排序后:\t");
52 selection.printAll(array);
53 }
54
55 }