c - C 中的堆排序,索引 0 问题

标签 c vector heapsort

对于学校项目,我决定通过编写 HeapSort 来解决问题,但我遇到了问题。 (“vector ”是要排序的 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,所以我并没有真正正确地处理堆。有人可以帮我解决这个问题吗?

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

最佳答案

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

关于c - C 中的堆排序,索引 0 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5825683/

相关文章:

c++ - 从多个 USB 摄像头捕获帧 - OpenCV,C++

c++ - vector 中的线程无法连接

使用线程 : can it be optimized further? 对 HUGE vector 的 C++ 操作

java - 为什么 bubbleDown 方法没有按预期工作(堆排序)?

sorting - 事件模拟是否需要优先级队列?

c - 如何使 printf 在 C 中正确打印用户输入 argv 的 strtok

C 全局变量和局部变量

c - 与聚合或 union 类型相关的严格别名

c - 当我处于无限 while 循环中时如何使用 malloc

tree - 如何最好地描述 TreeSort 和 HeapSort 算法是什么?