题目很明确,就是让你写一个插入排序和堆排序,我有以下几点收获:
- 由于c++数组是从0开始编号,所以如果一个堆(完全二叉树)的一个非叶子结点i,那么它的左孩子是2i+1,右孩子是2i+2。
- 如果从1开始编号,那么左孩子是2i,右孩子是2i+1;
#include <iostream>
#include <string>
#include <set>
#include <map>
#include<queue>
#include<stack>
#include<algorithm>
//new and delete
//A1098 Insertion or Heap Sort
using namespace std;
typedef int ElemType;
void PrintS(vector<ElemType> heap) {
int n = heap.size();
for (int i = 0; i < n; i++) {
cout << heap[i];
if (i < n - 1)
cout << " ";
else
cout << endl;
}
}
//heap[low] is the top Element of Heap. heap[high] is the end
void DownAdjust(int low, int high, vector<ElemType> &heap) {
//大顶堆
int i = low;
int j = 2 * i+1; //左孩子
while (j <= high) {
if (j + 1 <= high && heap[j] < heap[j + 1]) {
//有右孩子且右孩子比较大
j = j + 1;
}
if (heap[i] < heap[j]) { //需要调整
swap(heap[i], heap[j]);
i = j;
j = 2 * i+1;
}
else
break;
}
}
//Create a heap
void CreateHeap(vector<ElemType> &heap) {
int n = heap.size();
for (int i = n / 2; i >= 0; i -- ) {
DownAdjust(i, n-1, heap);
}
}
int main() {
int N;
cin >> N;
//initial and target sequence
vector<ElemType> ini_seq, tar_seq;
for (int i = 0; i < N; i++) {
ElemType temp;
cin >> temp;
ini_seq.push_back(temp);
}
for (int i = 0; i < N; i++) {
ElemType temp;
cin >> temp;
tar_seq.push_back(temp);
}
//Insertion/Heap sort
vector<ElemType> Isort, Hsort;
Isort = Hsort = ini_seq;
int flag = 0;
//插入排序, flag=1
for (int i = 2; i <= N; i++) {
sort(&Isort[0], &Isort[0] + i);
if (Isort == tar_seq) {
flag = 1;
sort(&Isort[0], &Isort[0] + i+1);
break;
}
}
//堆排序,flag=2
CreateHeap(Hsort);
for (int i = N - 1; i > 0; i--) {
swap(Hsort[0], Hsort[i]);
DownAdjust(0, i - 1, Hsort);
//PrintS(Hsort);
if (Hsort == tar_seq) {
flag = 2;
i--;
swap(Hsort[0], Hsort[i]);
DownAdjust(0, i - 1, Hsort);
break;
}
}
//输出
if (flag == 1) {
cout << "Insertion Sort\n";
for (int i = 0; i < N; i++) {
cout << Isort[i];
if (i < N - 1)
cout << " ";
else
cout << endl;
}
}
else if (flag == 2) {
cout << "Heap Sort\n";
for (int i = 0; i < N; i++) {
cout << Hsort[i];
if (i < N - 1)
cout << " ";
else
cout << endl;
}
}
return 0;
}