我正在尝试转换我用于向量的max-heapify函数来处理整数数组,但是,当我运行它时,我遇到了无限循环。
我相信我的算法的逻辑似乎是正确的,但是,我的siftdown函数似乎无法正常运行。
void Sort::heapify(int *array, int size){
for(int i = (size-2)/2;i >= 0;i--){
siftdown(array, i, size);
}
}
void Sort::siftdown(int *array, int i, int size){
if(i >= size || i < 0){
cout << "i is >= size of playerArray or i < 0. i: " << i << endl;
return;
}
cout<< "passed something" <<endl;
while(!isLeaf(array, i, size)){
cout<<"!isLeaf"<<endl;
int max = getLeft(i);
if(max + 1 < size && array[max] < array[max +1]){
max++;
cout << "added to max.";
}
if (array[i] > array[max]){
cout<< "array[i] is > than array[max]"<<endl;
return;
}
swap(i, max);
i = max;
}
cout<<"isLeaf"<<endl;
}
int Sort::getLeft(int index){
//gets the left most leaf
int left = 2*index+1;
return left;
}
bool Sort::isLeaf(int *array, int index, int size){
//A node is a leaf node if both left and right child nodes of it are NULL.
int left = 2*index+1;
int right = left+1;
if(left>size && right>size) return true;
return false;
}
非常感谢任何帮助。谢谢!
答案 0 :(得分:1)
撰写时(while
中Sort::siftdown()
的正文)
swap(i, max);
i = max;
您以i
和max
结尾,其旧值为i
;所以你重复
while(!isLeaf(array, i, size))
具有相同的值。
循环!