-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBobbleSort.java
More file actions
74 lines (57 loc) · 1.81 KB
/
BobbleSort.java
File metadata and controls
74 lines (57 loc) · 1.81 KB
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
package Sort;
/**
* FileName: BobbleSort
* Author: mac
* Date: 2019-01-21 16:27
* Description: 冒泡排序
* N个数字要排序完成,总共进行N-1轮排序,每i轮的排序次数为(N-i)次,所以可以用双重循环语句,外层控制循环多少趟,内层控制每一趟的循环次数
*/
public class BobbleSort {
public static int[] bobbleSort1(int[] aars) {
for (int i = 1; i < aars.length; i++) {
for (int j = 0; j < aars.length - i; j++) {
if (aars[j] > aars[j + 1]) {
int r = aars[j];
aars[j] = aars[j + 1];
aars[j + 1] = r;
}
}
}
return aars;
}
public static int[] bobbleSort2(int[] aars) {
int n = aars.length;
boolean swapped;
do {
swapped = false;
for (int i = 1; i < n; i++) {
if (aars[i - 1] > aars[i]) {
int r = aars[i - 1];
aars[i - 1] = aars[i];
aars[i] = r;
swapped = true;
}
}
n--;
} while (swapped);
return aars;
}
public static int[] bobbleSort3(int[] aars) {
int n = aars.length;
int newn; // 使用newn进行优化
do {
newn = 0;
for (int i = 1; i < n; i++) {
if (aars[i - 1] > aars[i]) {
int r = aars[i - 1];
aars[i - 1] = aars[i];
aars[i] = r;
// 记录最后一次的交换位置,在此之后的元素在下一轮扫描中均不考虑
newn = i;
}
}
n = newn;
} while (newn > 0);
return aars;
}
}