版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/alex1997222/article/details/83868741
堆排序是指使用堆结构对一个序列进行排序的过程,此处讨论递增排序的情况
考虑对一个堆来说,堆顶元素是最大的,因此在建堆完毕后,思路就是取出堆顶元素,然后将堆的最后一个元素替换至堆顶,再进行一次针对堆顶元素的向下调整--如此重复,直到堆中剩下最后一个元素为止
如此重复,直到堆中只剩下最后一个元素为止
我们可以直接用一个数组来表示堆,
const int maxn = 1001;
int heap[maxn], n = 10; //n表示元素个数
堆的调整函数,其中low是堆顶元素位置
void downAdjust(int low, int high) { //low表示最低的元素下标,high表示数组的最后一个元素的下标
int current = low, lchild = current * 2; //j表示左孩子
while (lchild <= high) { //如果左孩子存在
//如果右孩子存在,且右孩子的值大于当前结点值
if (lchild + 1 <= high && heap[lchild] < heap[lchild + 1]) {
lchild = lchild + 1; //改成右节点
}
if (heap[lchild] > heap[current]) {
swap(heap[lchild], heap[current]);
current = lchild;
lchild = current * 2;
}
else {
break;
}
}
}
堆的建立:我们根据数学原理可以知道,完全二叉树中叶子结点个数=结点个数/2;
所以我们只需从上至下对非叶子结点进行调整就可以了
//堆的建立
void createHeap() { //创建堆:把堆进行排序
for (int i = n / 2; i >= 1; i--) { //
downAdjust(i, n);
}
}
插入:新元素先插入底部,然后自下而上与父类进行比较并放置到合适的位置
void insert(int x) {
heap[++n] = x;
int current = n;
int father = n / 2;
while (father >= 1 && heap[current] > heap[father]) {
swap(heap[current], heap[father]);
current = father;
father = current / 2;
}
}
遍历:直接按序输出数组,层序遍历即可
void traverse() {
for (int i = 1; i <= n; ++i) {
cout << heap[i] << " ";
}
cout << endl;
}
堆排序:(依次将顶部元素与底部元素逐个交换,然后对堆到该底部元素的位置进行调整)
void heapSort() {
for (int i = n; i > 1; --i) {
swap(heap[1], heap[i]);
downAdjust(1, i-1);
traverse();
}
}
整体代码如下:
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1001;
int heap[maxn], n = 10; //n表示元素个数
void downAdjust(int low, int high) { //low表示最低的元素下标,high表示数组的最后一个元素的下标
int current = low, lchild = current * 2; //j表示左孩子
while (lchild <= high) { //如果左孩子存在
//如果右孩子存在,且右孩子的值大于当前结点值
if (lchild + 1 <= high && heap[lchild] < heap[lchild + 1]) {
lchild = lchild + 1; //改成右节点
}
if (heap[lchild] > heap[current]) {
swap(heap[lchild], heap[current]);
current = lchild;
lchild = current * 2;
}
else {
break;
}
}
}
void createHeap() { //创建堆:把堆进行排序
for (int i = n / 2; i >= 1; i--) { //
downAdjust(i, n);
}
}
void insert(int x) {
heap[++n] = x;
int current = n;
int father = n / 2;
while (father >= 1 && heap[current] > heap[father]) {
swap(heap[current], heap[father]);
current = father;
father = current / 2;
}
}
void traverse() {
for (int i = 1; i <= n; ++i) {
cout << heap[i] << " ";
}
cout << endl;
}
void heapSort() {
for (int i = n; i > 1; --i) {
swap(heap[1], heap[i]);
downAdjust(1, i-1);
traverse();
}
}
int main() {
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> heap[i];
}
system("PAUSE");
return 0;
}