class HeapSort {
public:
void MaxHeapFixup(int a[], int i){
int j, temp;
temp = a[i];
j = (i - 1) / 2;
while (j >= 0 && i != 0){ //往上查找应该放的位置
if (a[j] >= temp){
break;
}
a[i] = a[j];
i = j;
j = (i - 1) / 2;
}
a[i] = temp;
}
void MaxHeapAddNumber(int a[], int n, int nNum) //插入时
{
a[n] = nNum;
MaxHeapFixup(a, n); //插入数a[n]
}
void Swap(int &a, int &b){
int temp = a;
a = b;
b = temp;
}
// 从i节点开始调整,n为节点总数 从0开始计算 i节点的子节点为 2*i+1, 2*i+2
void MaxHeapFixdown(int *a, int i, int n){
int j = (i * 2) + 1;
int temp = a[i];
while (j < n){
if (j + 1 < n && a[j + 1] > a[j]){ //找出子节点最大的下标
j++;
}
if (a[j] <= temp){ // 此时符合大顶堆规则
break;
}
a[i] = a[j]; //把较大的子结点往上移动,替换它的父结点
i = j;
j = (i * 2) + 1;
}
a[i] = temp;
}
//在最大堆中删除数
void MaxHeapDeleteNumber(int a[], int n)
{
Swap(a[0], a[n - 1]);
MaxHeapFixdown(a, 0, n - 1);
}
//建立最大堆
void MakeMaxHeap(int a[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
MaxHeapFixdown(a, i, n);
}
void MaxheapsortTodescendarray(int a[], int n)
{
MakeMaxHeap(a, n);
for (int i = n - 1; i >= 1; i--)
{
Swap(a[i], a[0]);
MaxHeapFixdown(a, 0, i);
}
}
int* heapSort(int* A, int n) {
MaxheapsortTodescendarray(A, n);
return A;
}
};
堆排序
最新推荐文章于 2024-09-04 23:05:17 发布