题目描述
堆排序是一种利用堆结构进行排序的方法,它只需要一个记录大小的辅助空间,每个待排序的记录仅需要占用一个存储空间。
首先建立小根堆或大根堆,然后通过利用堆的性质即堆顶的元素是最小或最大值,从而依次得出每一个元素的位置。
堆排序的算法可以描述如下:

在本题中,读入一串整数,将其使用以上描述的堆排序的方法从小到大排序,并输出。
输入
输入的第一行包含1个正整数n,表示共有n个整数需要参与排序。其中n不超过100000。
第二行包含n个用空格隔开的正整数,表示n个需要排序的整数。
输出
只有1行,包含n个整数,表示从小到大排序完毕的所有整数。
请在每个整数后输出一个空格,并请注意行尾输出换行。
样例输入
10
2 8 4 6 1 10 7 3 5 9
样例输出
1 2 3 4 5 6 7 8 9 10
提示
在本题中,需要按照题目描述中的算法完成堆排序的算法。
堆排序对于元素数较多的情况是非常有效的。通过对算法的分析,不难发现在建立含有n个元素的堆时,总共进行的关键字比较次数不会超过4n,且n个节点的堆深度是log2n数量级的。因此,堆排序在最坏情况下的时间复杂度是O(nlog2n),相对于快速排序,堆排序具有同样的时间复杂度级别,但是其不会退化。堆排序较快速排序的劣势是其常数相对较大。
思路一:每输入一个数字便向上调整一次,每输出一个数字便向下调整一次。
#include <cstdio>
#include <algorithm>
using namespace std;
int heap[100010], n;
void upAdjust(int low, int high) {
int i = high;
int j = i / 2;
while (j >= low) {
if (heap[j] > heap[i]) {
swap(heap[j], heap[i]);
i = j;
j = i / 2;
} else {
break;
}
}
}
void downAdjust(int low, int high) {
int i = low;
int j = i * 2;
while (j <= high) {
if (j + 1 < high && heap[j + 1] < heap[j]) {
j = j + 1;
}
if (heap[j] < heap[i]) {
swap(heap[i], heap[j]);
i = j;
j = i * 2;
} else {
break;
}
}
}
void deleteTop() {
heap[1] = heap[n--];
downAdjust(1, n);
}
int main() {
while (scanf("%d", &n) != EOF) {
for (int i = 1; i <= n; ++i) {
scanf("%d", &heap[i]);
upAdjust(1, i);
}
while (n != 0) {
printf("%d ", heap[1]);
deleteTop();
}
printf("\n");
}
return 0;
}
思路二:输入所有数字后建堆,再进行堆排序,最后一次性输出。
#include <cstdio>
#include <algorithm>
using namespace std;
int heap[100010], n;
void downAdjust(int low, int high) {
int i = low;
int j = i * 2;
while (j <= high) {
if (j + 1 < high && heap[j + 1] < heap[j]) {
j = j + 1;
}
if (heap[j] < heap[i]) {
swap(heap[i], heap[j]);
i = j;
j = i * 2;
} else {
break;
}
}
}
void createHeap() {
for (int i = n / 2; i >= 1; i--) {
downAdjust(i, n);
}
}
void heapSort() {
createHeap();
for (int i = n; i > 1; i--) {
swap(heap[i], heap[1]);
downAdjust(1, i - 1);
}
}
int main() {
while (scanf("%d", &n) != EOF) {
for (int i = 1; i <= n; i++) {
scanf("%d", &heap[i]);
}
heapSort();
for (int i = n; i >= 1; i--) {
printf("%d ", heap[i]);
}
printf("\n");
}
return 0;
}
本文详细介绍了如何使用堆排序算法对一串整数进行从小到大的排序,包括两种思路的实现代码和堆排序的时间复杂度分析。重点在于理解堆的构建和调整过程,以及堆排序在大规模数据排序中的优势。
1160

被折叠的 条评论
为什么被折叠?



