-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;
}
あなたは正確に「失敗」とはどういう意味ですか役に立てば幸い
に渡しますか? – Dacaspexアサーションは渡していません。つまり: 'position'は' array-> size'よりも大きいです。私はアサーションを持っていない場合、これは、範囲外のエラーのインデックスを引き起こすが、いずれかの方法では動作しません。 – 123
デバッガを使用するか、コードにprintfsを追加する必要があるため、アサートに失敗したときに変数の値を見ることができます。ところで、私は問題が 'indexSmallest'にあると感じましたが、あなたはそのコードを表示していません。 [最小完全な検証可能な例](http://stackoverflow.com/help/mcve)を参照してください。 – user3386109