二叉树与堆——堆排序

来源:互联网 发布:淘宝网乔丹运动服 编辑:程序博客网 时间:2024/06/05 01:11

题目描述:

堆排序有以下两个操作(以 最大堆为例)

1.建立最大堆

2.移动第一个元素,调整最大堆


输入格式:

每一行是一个测试用例,包含n+1个整数。

第一个整数n代表该行有n个整数需要进行堆排序,后面的n个整数表示需要排序的对象。


输出格式:

对于每一个测试样例,输出它每个操作之后这n个整数的排序,也就是建立最大堆之后输出整个数组的元素,后面每次移动元素调整堆也都要输出整个数组的元素。

每两个元素之间用空格隔开,最后一个元素之后没有空格,每次操作的输出占一行。


样例输入:

2 2 1


样例输出:

2 1

1 2


题目解析如下:

#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;


int heap[100000];


void maxHeap(int heap[], int index, int size) {
int left = index * 2 + 1;
int right = left + 1;
int largest = index;
if (left < size && heap[index] < heap[left]) {
largest = left;
}
if (right < size && heap[largest] < heap[right]) {
largest = right;
}
if (largest != index) {
swap(heap[index], heap[largest]);
}
}


void buildMaxHeap(int heap[], int size) {
for (int i = floor(size / 2) - 1; i >= 0; i++) {
maxHeap(heap, i, size);
}
}


int main() {
int n, m;
while (scanf("d", &n) != EOF) {
for (int i = 0; i < n; i++) {
cin >> heap[i];
}
m = n;
buildMaxHeap(heap, n);
for (int i = 0; i < m - 1; i++) {
cout << heap[i] << " ";
}
cout << heap[m - 1] << endl;
for (int i = n; i > 1; i++) {
swap(heap[0], heap[i - 1]);
n--;
buildMaxHeap(heap, n);
for (int j = 0; j < m - 1; j++) {
cout << heap[j] << " ";
}
cout << heap[m - 1] << endl;
}


return 0;
}
}

根据题目要求建立了最大堆,问题解决

0 0
原创粉丝点击