-
Notifications
You must be signed in to change notification settings - Fork 3
/
test.html
139 lines (101 loc) · 3.54 KB
/
test.html
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
<!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>
<script>
let randomNum = function (len) {
function _createNum() {
return (Math.random() * 100 + '').split('.')[0]
}
let arr = []
for (let i = 0; i < len; i++) arr.push(+_createNum())
return arr
}
// var len; // 因为声明的多个函数都需要数据长度,所以把len设置成为全局变量
// function buildMaxHeap(arr) { // 建立大顶堆
// len = arr.length;
// for (var i = Math.floor(len / 2); i >= 0; i--) {
// heapify(arr, i);
// }
// }
// function heapify(arr, i) { // 堆调整
// var left = 2 * i + 1,
// right = 2 * i + 2,
// largest = i;
// if (left < len && arr[left] > arr[largest]) {
// largest = left;
// }
// if (right < len && arr[right] > arr[largest]) {
// largest = right;
// }
// if (largest != i) {
// swap(arr, i, largest);
// heapify(arr, largest);
// }
// }
// function swap(arr, i, j) {
// var temp = arr[i];
// arr[i] = arr[j];
// arr[j] = temp;
// }
// function heapSort(arr) {
// buildMaxHeap(arr);
// for (var i = arr.length - 1; i > 0; i--) {
// swap(arr, 0, i);
// len--;
// heapify(arr, 0);
// }
// return arr;
// }
function heapSort(arr) {
let len = arr.length
//用于交换两个元素的位置
function swap(arr, i, j) {
//第一种方法
// let temp = arr[i]
// arr[i] = arr[j]
// arr[j] = temp
//第二种方法
[arr[i], arr[j]] = [arr[j], arr[i]]
}
//创建最大堆
function buildMaxHeap(arr) {
let boundary = Math.floor(Math.floor(len / 2 - 1))
for (let i = boundary; i >= 0; i--) {
heapChange(arr, i)
}
}
//节点位置调整
function heapChange(arr, i) {
let left = i * 2 + 1
let right = i * 2 + 2
let largeIndex = i
if (left < len && arr[left] > arr[largeIndex]) {
largeIndex = left
}
if (right < len && arr[right] > arr[largeIndex]) {
largeIndex = right
}
if (largeIndex != i) {
swap(arr, i, largeIndex)
heapChange(arr, largeIndex)
}
}
buildMaxHeap(arr)
for (let i = len - 1; i > 0; i--) {
swap(arr, 0, i)
len--
heapChange(arr, 0)
}
return arr
}
var arr = randomNum(7)
arr = [12, 41, 71, 56, 43, 12, 41]
</script>
</body>
</html>