选择排序(Selection Sort)

Posted by 余腾 on 2019-02-21
Estimated Reading Time 2 Minutes
Words 461 In Total
Viewed Times

选择排序

是不稳定的排序方法。

  • 第一次从下标为 0 的开始下标为 0 的这个数与后面的 n-1 个进行比较;找出最小或者最大的放在下标为 0 的这个位置;
  • 第二次从下标为 1 的开始比较;查询剩下的最大或者最小值;放在下标为 1 的位置;以此类推;直到排序完成
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import java.time.Duration;
import java.time.LocalTime;
import java.util.Arrays;

/**
* 每次遍历找到最小值 与 arr[i] 进行交换 i 0~arr.length-1
* 选择排序 O(n^2) O(n^2) 不稳定 O(1) n小时较好
*/
public class SelectionSort {
public static void main(String[] args) {

int[] arr = {1, 3, 2, 45, 65, 33, 12};
System.out.println("交换之前:" + Arrays.toString(arr));


// Selection(arr);
// Selection2(arr);

System.out.println("-----testSelection------");
int[] testArray = new int[80000];
for (int i = 0; i < 80000; i++) {
testArray[i] = (int) (Math.random() * 800000);//生成一个 [0,800000) 内的数字
}

LocalTime start = LocalTime.now();
System.out.println("开始时间为:" + start);

Selection2(testArray);

LocalTime end = LocalTime.now();
System.out.println("结束时间为:" + end);

Duration time = Duration.between(start, end);
System.out.println("时间为:" + time.toMillis() + " 毫秒!");
}

// 0--1
// 0--2
// 0--3
// 0--4
// 1--2
// 1--3
// 1--4
// 2--3
// 2--4
// 3--4

public static void Selection2(int[] arr) {

int count = 0;
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i; //假定最小值索引
int min = arr[i];
for (int j = i + 1; j < arr.length; j++) {
if (min > arr[j]) {
min = arr[j];
minIndex = j;
}
}

if (minIndex != i) {
count++;
arr[minIndex] = arr[i];
arr[i] = min;
}
// System.out.println("第" + (i + 1) + "轮交换后:" + Arrays.toString(arr));
}
System.out.println("交换次数:"+count);
}

public static void Selection(int[] arr) {
for (int j = 1; j < arr.length; j++) {
for (int i = j; i < arr.length; i++) {
int temp;
if (arr[j - 1] > arr[i]) {
temp = arr[j - 1];
arr[j - 1] = arr[i];
arr[i] = temp;
}
}
System.out.println("第" + j + "轮交换后:" + Arrays.toString(arr));
}
}
}

感谢阅读


If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !