堆排序的一趟是对堆进行建造的一趟,而不是交换堆顶和数组尾部的序列。。
//
// main.cpp
// test 5
//
// Created by Jacky Roth on 2019/2/26.
// Copyright © 2019 Jacky Roth. All rights reserved.
//
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <vector>
#include <unordered_map>
using namespace std;
vector<int>heap,ori,now,he_now;
int N;
void up_down(int index,int high){
if (2*index>high) {
return;
}
//选出两个孩子中最大的一个
int kid=2*index;
if (2*index+1<=high&&heap[2*index+1]>heap[2*index]) {
kid++;
}
if (heap[index]>=heap[kid]) {
return;
}else{
swap(heap[index], heap[kid]);
up_down(kid,high);
}
}
void creat_heap(){
for (int i=N/2; i>=1; i--) {
up_down(i,N);
}
}
int main(int argc, const char * argv[]) {
int data;
scanf("%d",&N);
heap.push_back(0);
he_now.push_back(0);
for (int i=0; i<N; i++) {
scanf("%d",&data);
ori.push_back(data);
heap.push_back(data);
}
for (int i=0; i<N; i++) {
scanf("%d",&data);
now.push_back(data);
he_now.push_back(data);
}
bool tag=0;
int k=2;
for (; k<=N; k++) {
sort(ori.begin(), ori.begin()+k);
if (ori==now) {
tag=1;
break;
}
}
if (tag) {
printf("Insertion Sort\n");
sort(ori.begin(), ori.begin()+k+1);
for (int i=0; i<ori.size(); i++) {
printf("%d",ori[i]);
if (i<ori.size()-1) {
printf(" ");
}else{
printf("\n");
}
}
}else{
printf("Heap Sort\n");
creat_heap();
int k;
for ( k=N; k>1; k--) {
if (heap==he_now) {
break;
}
swap(heap[1], heap[k]);
up_down(1, k-1);
}
if (k>1) {
swap(heap[1], heap[k]);
up_down(1, k-1);
}
for (int i=1; i<=N; i++) {
printf("%d",heap[i]);
if (i<N) {
printf(" ");
}else{
printf("\n");
}
}
}
return 0;
}