-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort-bubble.html
More file actions
57 lines (51 loc) · 1.71 KB
/
sort-bubble.html
File metadata and controls
57 lines (51 loc) · 1.71 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
<script>
function bubbleSort(array) {
let len = array.length
// 找出 len 个最大值
for (let i = 0; i < len - 1; i++) {
// 找出 len个最大值的方法:不断 在 len-已找出的最大值 = 剩下的数值中找到最大值
for (let j = 0; j < len - i - 1; j++) {
if (array[j] > array[j + 1]) {
// 利用es6的解构赋值减少临时变量的声明。
[array[j], array[j + 1]] = [array[j + 1], array[j]]
}
}
}
console.log(array);
}
function bubbleSortUpgrade(array) {
let high = array.length - 1
let low = 0
while (high > low) {
// 找一个最大值
for (let j = low; j < high; ++j) {
if (array[j] > array[j + 1]) {
// 利用es6的解构赋值减少临时变量的声明。
[array[j], array[j + 1]] = [array[j + 1], array[j]]
}
}
--high
// 找一个最小值
for (let j = high; j > low; --j) {
if (array[j] < array[j - 1]) {
// 利用es6的解构赋值减少临时变量的声明。
[array[j], array[j - 1]] = [array[j - 1], array[j]]
}
}
++low
}
console.log('array: ', array);
}
bubbleSortUpgrade([5, 3, 4, 2, 6, 1, 8, 7])
</script>
</html>