调整堆函数会导致索引范围断言失败

时间:2016-05-15 16:43:47

标签: c heap

我已经构建了一个adjust heap函数,但我的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()功能:

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

我的assert(position < array->size)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;
}

1 个答案:

答案 0 :(得分:0)

将数组传递给索引最小的目的是什么?该功能看起来不对。无论基于什么

,我总是会小于j
int leftChild = 2 * pos + 1;
int rightChild = 2 * pos + 2;

如果你在谈论这些孩子所包含的实际数据,那么它可能会有所不同。 也许传递

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

我希望有帮助