堆排序

#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
//父亲节点索引
int PARENT(int i)
{
return ceil(i / 2);
}
//左孩子节点索引
int LEFT(int i)
{
return 2 * i+1;
}
//右孩子节点索引
int RIGHT(int i)
{
return 2 * (i + 1);
}
//最大堆调整，将相应的比较关系改为小于即为最小堆调整
template<typename T>
void MAX_HEAPIFY(vector<T>& heap, int i,int heapSize)
{
int l = LEFT(i);
int r = RIGHT(i);
int largest=0;
if (l <= heapSize - 1 && heap[l] > heap[i])
largest = l;
else
largest = i;
if (r <= heapSize - 1 && heap[r] > heap[largest])
largest = r;
if (largest != i)
{
swap(heap[i], heap[largest]);
MAX_HEAPIFY(heap, largest,heapSize);
}
}
//创建最大堆
template<typename T>
void BUILD_MAX_HEAP(vector<T>& heap)
{
for (int i = floor((heap.size() - 1) / 2); i >= 0; i--)
{
MAX_HEAPIFY(heap, i, heap.size());
}
}
//堆排序
//将根节点与堆最后一位交换，对剪除最后一位后的新堆继续最大（小）调整，
//不断重复上述过程直到堆的大小为2
template<typename T>
void HEAP_SORT(vector<T>& heap)
{
BUILD_MAX_HEAP(heap);
for (int i = heap.size() - 1; i >= 2; i--)
{
swap(heap[0], heap[i]);
MAX_HEAPIFY(heap, 0, i);
}
}
int main()
{
//int a[10] = { 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 };
int a[15] = { 2, 4, 7, 1, 4, 8, 9, 31, 83, 28, 48, 94, 87, 16, 36 };
vector<int> heap(a, a + 15);

//没有构建最大堆前
cout << "没有构建最大堆前:\n";
for (auto x : heap)
cout << x << " ";
cout << endl;
//构建最大堆后
BUILD_MAX_HEAP(heap);
cout << "构建最大堆后:\n";
for (auto x : heap)
cout << x << " ";
cout << endl;
//堆排序后
HEAP_SORT(heap);
cout << "堆排序后:\n";
for (auto x : heap)
cout << x << " ";
cout << endl;

system("pause");
return 0;
}

d-ary heaps 多叉树堆排序C++实现

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120