2016-04-26 12 views
0

我想轉換一個max-heapify函數,我用於一個向量與排序整數整數的數組工作,但是,當我運行它時,我正在運行一個無限循環。最大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; 
} 

任何幫助將不勝感激。謝謝!

+2

「_I我相信我的算法的邏輯似乎是正確的。」您是否通過聲明來調試您的代碼聲明? –

回答

1

當你寫(在whileSort::siftdown()體)

swap(i, max); 
    i = max; 

你與imaxi舊值結束;所以你重複

while(!isLeaf(array, i, size)) 

具有相同的值。

Loop!

+0

哦!我的問題是,我試圖交換數組[我]和數組[最大]的值,但最終只是交換我和最大。 謝謝! – ecatalano