利用最小堆的性质。
每次都移除最顶端的元素,然后重新排序成最小堆,如此循环。
#include<iostream>
#include"MinHeap.h"
using namespace std;
int main()
{
int Cnt = 9; int x;
int A[] = { -2, 1, 7, 8, 0, 6, 5, 5, 4 };
cout << "The array is: ";
for (int i = 0; i != Cnt; i++)
cout << A[i] << " ";
cout << endl;
MinHeap<int> Heap(A, Cnt);//创建最小堆
//cout << "After sort" <<": ";
while (Cnt > 0){
Heap.Min(Heap, Cnt);
Heap.Remove(x);//删除一个元素
cout << x << " ";
Cnt--;
}
return 0;
}
#define DefaultSize 10
template<class T>
class MinHeap{
public:
MinHeap(int sz = DefaultSize);
MinHeap(T arr[], int n);
~MinHeap(){ delete[]heap; }
bool Insert(const T&x);
bool Remove(T &x);
bool IsEmpty()const { return (currentSize == 0) ? true : false; }
bool IsFull()const { return(currentSize == maxHeapSize) ? true : false; }
void MakeEmpty(){ currentSize = 0; }
void siftDown(int start, int m );
void siftUp(int start);
void Min(MinHeap<T>&H,int n);
//private:
T *heap;
int currentSize;
int maxHeapSize;
};
template<class T>
MinHeap<T>::MinHeap(int sz){
maxHeapSize = (DefaultSize < sz) ? sz : DefaultSize;
heap = new T[maxHeapSize];
if (heap == NULL){ cerr << "faild!" << endl; exit(1); }
currentSize = 0;
}
template<class T>
MinHeap<T>::MinHeap(T arr[], int n){
maxHeapSize = (DefaultSize < n) ? n : DefaultSize;
heap = new T[maxHeapSize];
if (heap == NULL){ cerr << "faild!" << endl; exit(1); }
for (int i = 0; i < n; i++)
heap[i] = arr[i];
currentSize = n;
int currentPos = (currentSize - 2) / 2;
while (currentPos >= 0){
siftDown(currentPos, currentSize - 1);
currentPos--;
}
}
template<class T>//下滑调整算法
void MinHeap<T>::siftDown(int start, int m){
int i = start, j = 2 * i + 1;
T temp = heap[i];
while (j <= m){
if (j<m &&heap[j]>heap[j + 1])
j++;
if (temp <= heap[j])
break;
else { heap[i] = heap[j]; i = j; j = 2 * j + 1; }
}
heap[i] = temp;
}
template<class T>
bool MinHeap<T>::Remove(T &x){
if (!currentSize) { cout << "Heap empty!" << endl; return false; }
x = heap[0]; heap[0] = heap[currentSize - 1];//最后一个元素填补到根节点
currentSize--;
siftDown(0, currentSize - 1);
return true;
}
template<class T>
void MinHeap<T>::Min(MinHeap<T>&H,int n){
H.currentSize = n;
int currentPos = (H.currentSize - 2) / 2;
while (currentPos >= 0){
siftDown(currentPos, currentSize - 1);
currentPos--;
}
}