2016-05-15 5 views
-1

調整ヒープ関数を作成しましたが、assert(position < array->size)が失敗していて、なぜその理由がわかりません。 ヒープ関数を調整するとインデックス範囲アサーションが失敗する

void adjustHeap(DynamicArray* heap, int max, int pos, compareFunction compare) 
{ 
    // FIXME: implement 
    int leftChild = 2 * pos + 1; 
    int rightChild = 2 * pos + 2; 
    int idxSmallest = indexSmallest(heap, leftChild, rightChild); 
    if(rightChild < max) { /* we have two children */ 
     if(dyGet(heap, pos) > dyGet(heap, idxSmallest)) { 
      dySwap(heap,pos,idxSmallest); 
      adjustHeap(heap, max, idxSmallest, compare); 
     } 
    } 
    else if (leftChild < max) { /* we have one child */ 
     if(dyGet(heap, pos) > dyGet(heap, leftChild)) { 
      dySwap(heap,pos,leftChild); 
      adjustHeap(heap, max, leftChild, compare); 
     } 
    } 
    else { 
     return; 
    } 
} 

マイ dyGet()機能:

void testAdjustHeap(CuTest* test) 
{ 
    const int n = 100; 
    Task* tasks = createTasks(n); 
    for (int j = 0; j < n; j++) 
    { 
     DynamicArray* heap = dyNew(1); 
     for (int i = 0; i < n; i++) 
     { 
      dyAdd(heap, &tasks[i]); 
     } 
     for (int i = 0; i < n; i++) 
     { 
      dyPut(heap, &tasks[rand() % n], 0); 
      adjustHeap(heap, dySize(heap) - 1, 0, taskCompare); 
      assertHeapProperty(test, heap); 
     } 
     dyDelete(heap); 
    } 
    free(tasks); 
} 

'indexSmallest' 関数:

int indexSmallest(struct DynamicArray * v, int i, int j) { /* return index of smallest element */ 
    if(i < j) { 
     return i; 
    } 
    return j; 
} 
+0

あなたは正確に「失敗」とはどういう意味ですか役に立てば幸い

indexSmallest(v->data[leftChild], v->data[rightChild]) 

に渡しますか? – Dacaspex

+0

アサーションは渡していません。つまり: 'position'は' array-> size'よりも大きいです。私はアサーションを持っていない場合、これは、範囲外のエラーのインデックスを引き起こすが、いずれかの方法では動作しません。 – 123

+1

デバッガを使用するか、コードにprintfsを追加する必要があるため、アサートに失敗したときに変数の値を見ることができます。ところで、私は問題が 'indexSmallest'にあると感じましたが、あなたはそのコードを表示していません。 [最小完全な検証可能な例](http://stackoverflow.com/help/mcve)を参照してください。 – user3386109

答えて

0

TYPE dyGet(DynamicArray* array, int position) 
{ 
    assert(position < array->size); 
    return array->data[position]; 
} 

は私のassert(position < array->size)は、次の試験を使用してdyGet()に失敗しています

インデックスを最小のインデックスに渡す目的は何ですか?関数が間違っています。

int leftChild = 2 * pos + 1; 
int rightChild = 2 * pos + 2; 

これらの子供に含まれる実際のデータを話していると、私はいつもjより小さくなることがあります。 は、おそらく私が

関連する問題