1⃣️插入排序用sort函数实现更方便。对排序模板,建堆,向下调整,堆排序,(向上调整,插入,删除)
2⃣️堆只有对顶是最大或最小,且每个小分堆也是,但整体并不一定有序
#include<iostream>
#include<vector>
using namespace std;
vector<int> initial,result,temp;
int n,sign=0;
bool issame(){
int num=n-temp.size();
for(int i=0;i<num;i++){
temp.push_back(initial[temp.size()]);
}
if(temp==result){
for(int i=0;i<num;i++)
temp.pop_back();
return true;}
else{
for(int i=0;i<num;i++)
temp.pop_back();
return false;
}
}
void insertsort(){
vector<int>::iterator it1,it2;
temp.resize(1);
temp[0]=initial[0];
for(it1=initial.begin()+1;it1!=initial.end();it1++){
for(it2=temp.begin();it2!=temp.end();it2++){
if(*it2>*it1)
{
temp.insert(it2,*it1); //插入temp中比它大的值的位置,后边的值依次后移
break;
}
}
if(it2==temp.end())
temp.push_back(*it1); //不存在比它大的值就放在最后
if(sign==1)
return;
if(issame()){
sign=1;
}
}
}
void downadjust(int low,int high){
int i=low,j=i*2;
while(j<=high){
if(j+1<=high&&temp[j+1]>temp[j])
j=j+1;
if(temp[j]>temp[i]){
int t=temp[j];
temp[j]=temp[i];
temp[i]=t;
i=j;
j=i*2;
}
else
break;
}
}
void heapsort(){
initial.insert(initial.begin(),-999);
result.insert(result.begin(),-999);
temp=initial;
for(int i=n/2;i>=1;i--)
downadjust(i,n);
for(int i=n;i>1;i--){
swap(temp[i],temp[1]);
downadjust(1,i-1);
if(sign==2)
return;
if(temp==result)
sign=2;
}
}
int main(){
int x;
cin>>n;
temp.resize(101);
for(int i=0;i<n;i++)
{
cin>>x;
initial.push_back(x);
}
for(int i=0;i<n;i++)
{
cin>>x;
result.push_back(x);
}
insertsort();
if(sign==1){
cout<<"Insertion Sort"<<endl;
for(int i=0;i<n;i++)
{
cout<<temp[i];
if(i!=n-1)
cout<<" ";
}
}
else{
cout<<"Heap Sort"<<endl;
heapsort();
for(int i=1;i<=n;i++)
{
cout<<temp[i];
if(i!=n)
cout<<" ";
}
}
return 0;
}