在C中的Heapsort,索引0问题

时间:2011-04-28 22:17:21

标签: c vector heapsort

对于学校项目我决定通过编写HeapSort来解决问题,但我有一个问题。 (“vector”是要排序的向量,“n”是“vector”中元素的数量)

这是我的代码:

void fixHeap(int position,int length)
{
    int next=2*position;
    int temp;

    while (next<=length)
    {
        if (next<length && vector[next]<vector[next+1])
        {
            next++;
        }
        if (vector[position]<vector[next])
        {
            temp=vector[position];
            vector[position]=vector[next];
            vector[next]=temp;
            position=next;
            next=2*position;
        }
        else
        {
            return;
        }
    }
}

void heapSort()
{
    int counter;
    int temp;

    for(counter=(n-1)/2;counter!=0;counter--)
    {
        fixHeap(counter,n-1);
    }
    for(counter=n-1;counter>0;counter--)
    {
        temp=vector[counter]; 
        vector[counter]=vector[0];
        vector[0]=temp;
        fixHeap(0,counter-1);
    }
    display();
}

当我正在执行fixHeap(0,n-1)时,我将其置于0旁边,然后位置也为0,所以我并没有真正做正确的堆。有人可以帮我修理吗?

还有其他错误你发现我可能忽略了吗?

1 个答案:

答案 0 :(得分:1)

第i个节点的子节点为2 * i和2 * i + 1。但是如果要对数组中的每个项进行排序,则第一个节点位于索引0.您需要相应地修复子节点索引计算。