选择排序

选择排序原理图解

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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
public class SelectSortDemo {

public static void main(String[] args) {

// 定义一个数组
int[] arr = {24, 69, 80, 57, 13} ;

// 遍历方法
System.out.print("排序前: ");
BubbleSortDemo.print(arr) ;

// 选择排序
selectSort2(arr) ;

// 排序后的输出
System.out.print("排序后: ");
BubbleSortDemo.print(arr) ;

}

/**
* 选择排序
*/
private static void selectSort2(int[] arr) {

for(int index = 0 ; index < arr.length - 1 ; index++){
for(int x = 1 + index ; x < arr.length ; x++){
if(arr[x] < arr[index]){
int temp = arr[x] ;
arr[x] = arr[index] ;
arr[index] = temp ;
}
}
}

}


/**
* 选择排序的推导过程
*/
private static void selectSort(int[] arr) {

// 第一次排序
// 定义一个int类型的变量
int index = 0 ;

// 循环
for(int x = 1 + index ; x < arr.length ; x++){

if(arr[x] < arr[index]){
int temp = arr[x] ;
arr[x] = arr[index] ;
arr[index] = temp ;
}

}

// 第二次排序
index = 1 ;

// 循环
for(int x = 1 + index ; x < arr.length ; x++){

if(arr[x] < arr[index]){
int temp = arr[x] ;
arr[x] = arr[index] ;
arr[index] = temp ;
}

}

// 第三次排序
index = 2 ;

// 循环
for(int x = 1 + index ; x < arr.length ; x++){

if(arr[x] < arr[index]){
int temp = arr[x] ;
arr[x] = arr[index] ;
arr[index] = temp ;
}

}

// 第四次排序
index = 3 ;

// 循环
for(int x = 1 + index ; x < arr.length ; x++){

if(arr[x] < arr[index]){
int temp = arr[x] ;
arr[x] = arr[index] ;
arr[index] = temp ;
}

}

}

}