当我尝试自下而上构建d-max-heap时,我遇到了问题。当我在堆中使用低随机数时,代码可以工作,但是当我在堆中有大量数字时,代码不起作用。问题可能出在我的buildBottomUp函数中。我不确定我是否理解构建自下而上堆的正确方法是什么。这是我的代码:
这是我的头文件
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
template <typename Comparable>
void buildHeapBottomUp(Comparable arr[], int n, int d){
int current = 0;
for (int i = n-1; i > 0; i--){
current = i;
comparable++;
while (arr[current] > arr[(current - 1) / d]){
swap(arr[current], arr[(current - 1) / d]);
current = (current - 1) / d;
comparable++;
}
}
}
template <typename Comparable>
bool checkIfHeap(Comparable arr[], int n, int d){
bool dMaxHeap = true;
int current = 0;
for (int i = 1; i < n; i++){
current = i;
if(arr[current] > arr[(current - 1) / d]){
dMaxHeap = false;
}
}
return dMaxHeap;
}
template <typename Comparable>
Comparable removeFromHeap(Comparable heap[], int n, int d){
int current = n;
int numberOfChildren = d;
comparable = comparable + 1;
while (heap[0] < heap[numberOfChildren]){
swap(heap[0], heap[numberOfChildren]);
numberOfChildren = numberOfChildren--;
comparable = comparable + 1;
}
Comparable largest = heap[0];
swap(heap[0], heap[current]);
return largest;
}
template <typename Comparable>
void sortUsingBottomUpConstructionOfHeap(Comparable arr[], int n, int d){
comparable = 0;
int i = 0;
int counter = n;
Comparable *tmp = new Comparable[n];
while (i < n){
Comparable largest = removeFromHeap(arr, counter, d);
counter--;
tmp[counter] = largest;
buildHeapBottomUp(arr, counter, d);
i++;
}
counter = n - 1;
for (int k = 0; k < n; k++){
arr[k] = tmp[counter];
counter--;
}
}
#endif
这是我的主要文件
#include <iostream>
#include "functions.h"
using namespace std;
int comparable = 0;
int main(){
srand(time(NULL));
int n;
int d;
int insertValues = 0;
int *arr;
int maxValue;
cout << "How many elements do you want in your D-Heap? " << endl;
cin >> n;
cout << "How many children do you want in your D-Heap? " << endl;
cin >> d;
cout << "Choose max value in your D-heap ";
cin >> maxValue;
cout << "\n" << endl;
arr = new int[n];
fillArrayWithRandomNumbers(arr, n, maxValue);
cout << "Array before build\n" << endl;
/*for (int i = 0; i < n; i++){
cout << arr[i] << ", ";
}*/
}
comparable = 0;
buildHeapBottomUp(arr, n, d);
if (checkIfHeap(arr, n, d)){
cout << "\n\nArray after build Top down" << endl;
cout << "You got" << " " << comparable << " " << "comparison when you build max-heap\n" << endl;
/*for (int i = 0; i < n; i++){
cout << arr[i] << ", ";
}*/
comparable = 0;
sortUsingBottomUpConstructionOfHeap(arr, n, d);
cout << "\n\nArray after sort Top down" << endl;
cout << "You got" << " " << comparable << " " << "comparison when you sort max-heap\n" << endl;
/*for (int i = 0; i < n; i++){
cout << arr[i] << ", ";
}*/
}
else{
cout << "the build function for Bottom up do not work!" << endl;
}
cin.ignore();
getchar();
return 0;
}