File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed
Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * 堆排序
3+ *
4+ * Author: nameczz
5+ */
6+
7+ // 忽视数组的第一位
8+ class HeapSort {
9+ constructor ( originArray ) {
10+ this . originArray = originArray
11+ console . log ( this . originArray )
12+ }
13+ buildHeap ( ) {
14+ const arr = this . originArray
15+ const startIndex = Math . floor ( arr . length )
16+ for ( let i = startIndex ; i >= 1 ; i -- ) {
17+ this . heapify ( arr , arr . length , i )
18+ }
19+ return arr
20+ }
21+
22+ heapify ( arr , len , i ) {
23+ while ( true ) {
24+ let maxPos = i
25+ // 如果index i拥有叶左节点 并且左节点较大
26+ if ( i * 2 <= len && arr [ i ] < arr [ i * 2 ] ) {
27+ maxPos = i * 2
28+ }
29+ // 如果index i拥有叶右节点 与Max节点比较大小,选出父/左/右中最大的一个
30+ if ( i * 2 + 1 <= len && arr [ maxPos ] < arr [ i * 2 + 1 ] ) {
31+ maxPos = i * 2 + 1
32+ }
33+ if ( maxPos === i ) break // 循环直到i节点为最大值
34+ this . swap ( arr , i , maxPos ) // 交换位置, 父节点为父/左/右中最大的一个
35+ i = maxPos // i为左/右节点,并尝试向下查找更大的值
36+ }
37+ }
38+
39+ sort ( ) {
40+ const arr = this . buildHeap ( ) // 先建堆
41+ let len = arr . length - 1
42+ while ( len > 1 ) {
43+ this . swap ( arr , 1 , len ) // 交换顶元素和最后一位。顶元素永远是最大的。
44+ len --
45+ this . heapify ( arr , len , 1 ) //剩下的元素重新建堆 直到len === 1 停止
46+ }
47+ console . log ( arr )
48+ }
49+
50+ swap ( arr , i , max ) {
51+ let temp = arr [ i ]
52+ arr [ i ] = arr [ max ]
53+ arr [ max ] = temp
54+ }
55+ }
56+
57+ const arr = [ null ]
58+ let i = 0
59+ while ( i <= 10 ) {
60+ const num = Math . floor ( Math . random ( ) * 100 )
61+ arr . push ( num )
62+ i ++
63+ }
64+ const testHeap = new HeapSort ( arr )
65+ testHeap . sort ( )
You can’t perform that action at this time.
0 commit comments