File tree Expand file tree Collapse file tree 2 files changed +31
-3
lines changed Expand file tree Collapse file tree 2 files changed +31
-3
lines changed Original file line number Diff line number Diff line change 1+ import 'MaxHeap.dart' ;
2+
3+ /**
4+ * 堆排序
5+ */
6+ class HeapSort {
7+
8+ HeapSort () {
9+
10+ }
11+ static sort <E extends Comparable <E >>(List data) {
12+ MaxHeap <E > maxHeap = MaxHeap .withCapacity (10 );
13+ for (E e in data){
14+ maxHeap.add (e);
15+ }
16+ for (int i = data.length - 1 ; i >= 0 ; i -- )
17+ data[i] = maxHeap.extractMax ();
18+ }
19+
20+ }
Original file line number Diff line number Diff line change @@ -62,16 +62,15 @@ class MaxHeap<E extends Comparable<E>>{
6262
6363 // 取出堆中最大元素
6464 E extractMax (){
65-
6665 E ret = findMax ();
6766 _swap (0 , data! .length - 1 );
6867 data! .removeLast ();
69- siftDown (0 );
68+ _siftDown (0 );
7069
7170 return ret;
7271 }
7372
74- siftDown (int k){
73+ _siftDown (int k){
7574 while (_leftChild (k) < data! .length){
7675 int j = _leftChild (k); // 在此轮循环中,data[k]和data[j]交换位置
7776 if ( j + 1 < data! .length &&
@@ -85,6 +84,15 @@ class MaxHeap<E extends Comparable<E>>{
8584 }
8685 }
8786
87+ // 取出堆中的最大元素,并且替换成元素e
88+ E replace (E e){
89+
90+ E ret = findMax ();
91+ data! [0 ] = e;;
92+ _siftDown (0 );
93+ return ret;
94+ }
95+
8896 _swap (int i, int j){
8997 if (i < 0 || i >= data! .length || j < 0 || j >= data! .length)
9098 throw new Exception ("Index is illegal." );
You can’t perform that action at this time.
0 commit comments