PAT甲级1098 Insertion or Heap Sort (25 分)(堆排序)

参考:https://www.liuchuo.net/archives/2273
题源:

  1. https://pintia.cn/problem-sets/994805342720868352/problems/994805368847187968
  2. https://www.nowcoder.com/questionTerminal/a5e253b41eda4c79a57a86577d314454

测试用例的设计注意:非递减!=递增。

Sample Input 1:
10
3 1 2 8 7 5 9 4 6 0
1 2 3 7 8 5 9 4 6 0
Sample Output 1:
Insertion Sort
1 2 3 5 7 8 9 4 6 0
Sample Input 2:
10
3 1 2 8 7 5 9 4 6 0
6 4 5 1 0 3 2 7 8 9
Sample Output 2:
Heap Sort
5 4 3 1 0 2 6 7 8 9

//https://www.liuchuo.net/archives/2273
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void downAdjust(vector<int> &v, int low, int high) {
	int i = low, j = i * 2;
	while (j <= high) {
		if (j + 1 <= high && v[j + 1] > v[j])j = j + 1;
		if (v[j] > v[i]) {
			swap(v[i], v[j]);
			i = j;
			j = i * 2;
		}
		else {
			break;
		}
	}
}
int main() {
	int n;
	scanf("%d", &n);
	vector<int>a(n + 1), b(n + 1);
	for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
	for (int i = 1; i <= n; i++) scanf("%d", &b[i]);
	int p = 2;
	while (p <= n && b[p] >= b[p - 1])
		p++;//检查非递减
	int index = p;
	while (p <= n && b[p] == a[p])
		p++;//检查后续与原序列是否相符
	if (p == n + 1) {
		printf("Insertion Sort\n");
		sort(b.begin() + 1, b.begin() + index + 1);//多排一个,左闭右开,所以要加一。
	}
	else {
		printf("Heap Sort\n");
		//从后往前找位置
		p = n;
		while (p > 2 && b[1] <= b[p])
		{
			p--;
		}
		index = p;
		swap(b[1], b[index]);//大顶堆,堆排序,交换,向下调整
		downAdjust(b, 1, index - 1);//大顶交换下来之后就固定了,所以-1
	}
	//输出下一步排序结果
	printf("%d", b[1]);
	for (int i = 2; i <= n; i++)
		printf(" %d", b[i]);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/sinat_34524528/article/details/87940131