A1098 Insertion or Heap Sort(堆排序)

题目很明确,就是让你写一个插入排序和堆排序,我有以下几点收获:

  1. 由于c++数组是从0开始编号,所以如果一个堆(完全二叉树)的一个非叶子结点i,那么它的左孩子是2i+1,右孩子是2i+2。
  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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值