堆排序不能产生正确的输出

时间:2012-12-06 19:56:10

标签: c++ heap sorting heapsort

我正在编写一个使用堆排序对数组进行排序的函数。到目前为止,我有:

template <typename Item, typename SizeType>
void heap_sort(Item data[], SizeType size) {
vector<int> v(data,data+size);
SizeType unsorted = size;

make_heap(v.begin(),v.end());

while(unsorted > 1) {
    --unsorted;
    swap(data[0], data[unsorted]);
    reheapify_down(data,unsorted);
}
}

和:

template <typename Item, typename SizeType>
void reheapify_down(Item data[], SizeType size) {
SizeType current(0), big_child;
bool heap_ok = false;

while(!heap_ok && 2*current+1 < size) {
    if(2*current+2 > size)
        big_child = 2*current + 1;
    else if(data[2*current+1] > data[2*current+2])
        big_child = 2*current+1;
    else
        big_child = 2*current + 2;

    if(data[current] < data[big_child]) {
        swap(data[current],data[big_child]);
        current = big_child;
    }
    else
        heap_ok = true;
}
}

当我运行程序时,它会输出一个错误排序的数组。是否有一些我遗漏的东西或一些我忽略的错误?

1 个答案:

答案 0 :(得分:0)

只是一些建议。

首先,我会编写一个小代理类,它只会让您在集合中使用基于1的索引。堆中使用的所有索引数学都假定基于1的索引,并且在一个地方补偿基于0的索引比在所有代码中更容易。就目前而言,我有足够的时间跟踪索引以确保您的reheapify_down是正确的。这当然是正确的总体思路,但要确保所有的数学运算都是正确的,需要做很多工作。

其次,我会写一个check_heap(或其他),您可以用来验证make_heapreheapify_down(另外,我会决定“make_heap”或“heapify”,因此名称可以是“make_heap”和“remake_heap”,也可以是“heapify”和“reheapify”。

然而,除此之外,很难确定问题,特别是因为您没有在问题中包含make_heap的代码。如果它不能正常工作,其他人就没有希望了。

相关问题