//============================================================================
// Name : MyHeap.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
堆排序,首先得用O(n)时间复杂度构建一个堆,然后每一次从堆中删除最大的元素,重新调整堆,(nlogn)
#include <iostream>
#include <stdlib.h>
using namespace std;
void modify(int* a,int location, int size){
if(location<=size/2){
int leftchild = location*2;
int rightchild = location*2+1;
int max = location;
if(leftchild<=size&&a[leftchild]>a[max])
max=leftchild;
if(rightchild<=size&&a[rightchild]>a[max])
max=rightchild;
if(max!=location){
swap(a[location],a[max]);
modify(a,max,size);
}
}else
return;
}
void buildheap(int*a,int size){
for(int i =size/2;i>=1;i--){
modify(a,i,size);
}
}
void heapsort(int *a,int size){
buildheap(a,size);
for(int i =size;i>=1;i--){
swap(a[1],a[i]);
modify(a,1,i-1);
}
}
int main() {
// cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
int a[100]={0};
int size;
bool flag = true;
cout<<"welcome to heap sort"<<endl;
while(flag){
cout<<"input heap size:";
cin>>size;
cout<<"before sort "<<endl;
for(int i =1;i<=size;i++)
{
a[i]=rand()%100;
cout<<a[i]<<" ";
// if(i%10==0)
// cout<<endl;
}
cout<<endl;
heapsort(a,size);
cout<<"after sort "<<endl;
for(int i =1;i<=size;i++)
{
cout<<a[i]<<" ";
// if(i%10==0)
// cout<<endl;
}
cout<<endl;
if(size==100)
flag=false;
}
return 0;
}