堆实质上可以看作是以完全二叉树的结构来维护的一维数组
大顶堆:每个结点的值都大于或等于其左、右子结点的值
小顶堆:每个结点的值都小于或等于其左、右子结点的值
利用大顶堆实现由小到大排序代码如下:
/**
*Copyright @ 2019 Zhang Peng. All Right Reserved.
*Filename:
*Author: Zhang Peng
*Date:
*Version:
*Description:
**/
#include<iostream>
#include<vector>
using namespace std;
void heapSortCore(vector<int > & data, int i,int len)
{
if (i < len)
{
int left = 2 * i + 1;
int right = 2 * i + 2;
int swap = -1;
if (left<len && data[left]>data[i])
{
swap = left;
int temp = data[i];
data[i] = data[swap];
data[swap] = temp;
heapSortCore(data, swap, len);
}
if (right<len && data[right]>data[i])
{
swap = right;
int temp = data[i];
data[i] = data[swap];
data[swap] = temp;
heapSortCore(data, swap, len);
}
}
}
void heapSort(vector<int > & data,int len)
{
for (int i = len/2 - 1; i >= 0; i--)
{
heapSortCore(data, i, len);
}
}
int main()
{
vector<int > data = {7,3,8,3,6,5,1,2};
int datalen = data.size();
for (int i = 0; i < datalen; i++)
{
heapSort(data, datalen - i);
//每次堆排序会将最大的元素放在第一位,交换首尾数据,然后对其他数据进行堆排序
int temp = data[0];
data[0] = data[datalen - i - 1];
data[datalen - i - 1] = temp;
}
cout << "排序结果" << endl;
for (int i = 0; i < data.size(); i++)
cout << data[i] << " ";
cout << endl;
system("pause");
return 0;
}
如果将以上代码中与左、右子节点大小判断部分改为“<”,就变为了小顶堆,此时可以实现由大到小排序。
/**
*Copyright @ 2019 Zhang Peng. All Right Reserved.
*Filename:
*Author: Zhang Peng
*Date:
*Version:
*Description:
**/
#include<iostream>
#include<vector>
using namespace std;
void heapSortCore(vector<int > & data, int i,int len)
{
if (i < len)
{
int left = 2 * i + 1;
int right = 2 * i + 2;
int swap = -1;
if (left<len && data[left]<data[i])
{
swap = left;
int temp = data[i];
data[i] = data[swap];
data[swap] = temp;
heapSortCore(data, swap, len);
}
if (right<len && data[right]<data[i])
{
swap = right;
int temp = data[i];
data[i] = data[swap];
data[swap] = temp;
heapSortCore(data, swap, len);
}
}
}
void heapSort(vector<int > & data,int len)
{
for (int i = len/2 - 1; i >= 0; i--)
{
heapSortCore(data, i, len);
}
}
int main()
{
vector<int > data = {7,3,8,3,6,5,1,2};
int datalen = data.size();
for (int i = 0; i < datalen; i++)
{
heapSort(data, datalen - i);
//每次堆排序会将最小的元素放在第一位,交换首尾数据,然后对其他数据进行堆排序
int temp = data[0];
data[0] = data[datalen - i - 1];
data[datalen - i - 1] = temp;
}
cout << "排序结果" << endl;
for (int i = 0; i < data.size(); i++)
cout << data[i] << " ";
cout << endl;
system("pause");
return 0;
}