2️⃣1️⃣ 堆排序
😀 因为上节课学了堆,堆排序就是很简单的把数据放进堆,然后再取出来
#include <iostream>
#include <vector>
using namespace std;
class MaxHeap{
private:
int* heapArray;
int maxSize;
int currentSize;
void trickleUp(int); //向上渗透
void trickleDown(int);//向下渗透
public:
MaxHeap(int mx=10);
~MaxHeap();
bool Ismpty();
void Push(const int);
void Pop();
int Top()const;
};
MaxHeap::MaxHeap(int mx){
if(mx<1)
throw"max size must be >=1.";
maxSize = mx;
currentSize = 0;
heapArray = new int [maxSize];
}
MaxHeap::~MaxHeap(){
delete []heapArray;
}
bool MaxHeap::Ismpty(){
return currentSize==0;
}
void MaxHeap::Push(const int x){
if(currentSize == maxSize)
throw"MaxHeap is full.";
heapArray[currentSize] = x;
trickleUp(currentSize++);
}
void MaxHeap::trickleUp(int index){
int parent = (index-1)/2;
int bottom = heapArray[index];
while (index > 0 && bottom > heapArray[parent]){
heapArray[index] = heapArray[parent];
index = parent;
parent = (parent-1)/2;
}
heapArray[index] = bottom;
}
int MaxHeap::Top()const{
return heapArray[0];
}
void MaxHeap::Pop(){
heapArray[0] = heapArray [--currentSize];
trickleDown(0);
}
void MaxHeap::trickleDown(int index){
int largerChild;
int top = heapArray[index];
while(index < currentSize/2)
{
int LeftChild = 2*index + 1;
int RightChild = LeftChild + 1;
if(RightChild < currentSize && heapArray[LeftChild] < heapArray[RightChild])
largerChild = RightChild;
else largerChild = LeftChild;
if(top >= heapArray[largerChild])
break;
else heapArray[index] = heapArray[largerChild];
index = largerChild;
}
heapArray[index] = top;
}
int main(){
MaxHeap h(100);
vector<int> arr{62,3,90,27,33,8,12,9,43,66};
for(int i=0; i!=arr.size(); i++)
h.Push(arr[i]);
for(int i=0; i!=arr.size(); i++){
arr[i] = h.Top();
h.Pop();
}
for(int i=0; i!=arr.size(); i++)
cout << arr[i] << " ";
return 0;
}