代码之家  ›  专栏  ›  技术社区  ›  Aere

HeapSort问题[已关闭]

  •  0
  • Aere  · 技术社区  · 10 年前

    我的任务是根据伪代码将代码写入heapsort。它应该heapsort输入数组( 4 3 2 5 6 7 8 9 12 1 )然后用printHeap方法打印。我知道printHeap是有效的,因为我已经用它和一个名为buildHeap的方法(用来构建最大堆二进制树,但你们都已经知道:)一起使用了,而且它运行得很完美,所以我的问题在于heapSort。

    它正确地排序并按它应该的方式打印它(parent--child1,parent--2,等等),唯一的问题是,最大的最后一个值,也就是12,突然变成了24,我不知道为什么。

    代码如下:

    void heapSort(int a[], int n){
    int x = n+1;
    int i;
    int temp;
    buildMaxHeap(a, n);
    for (i = n; i >= 1; i--){
        temp = a[i];
        a[i] = a [0];
        a [0] = temp;
        x--;
        heapify(a, 0, x);
    }
    
    void printHeap(int a[], int n){
    
    int i;
    printf("graph g { \n");
    for (i = 0; i < n/2; i++){
        printf("%d -- %d\n", a[i], a[left(i)]);
        if (right(i) < n){
            printf("%d -- %d\n", a[i], a[right(i)]);
        }
    }
    printf("}\n");
    

    输出如下:

    1 2 3 4 5 6 7 8 9 24
    graph g {
    1 -- 2
    1 -- 3
    2 -- 4
    2 -- 5
    3 -- 6
    3 -- 7
    4 -- 8
    4 -- 9
    5 -- 24
    }
    

    为了让你知道我到底做了什么,我将在此处附加while.c文件: https://onedrive.live.com/redir?resid=8BC629F201D2BC63!26268&authkey=!AFqVlm9AptiZ_xM&ithint=file%2cc

    非常感谢你的帮助!

    干杯 阿里克

    1 回复  |  直到 10 年前
        1
  •  0
  •   Dimitar    10 年前

    嗯,你观察到了一种未定义的行为。(我个人在一个在线IDE上 0 而不是 12 ( 24 ).)

    尝试:

    void heapSort(int a[], int n)
    {
        int x = n; /* changed from n+1 */
        int i;
        int temp;
    
        buildMaxHeap(a, n);
        for (i = n-1; i >= 0; i--){ /*<-- changed*/
            temp = a[i];
            a[i] = a[0];
            a[0] = temp;
            x--;
            heapify(a, 0, x);
        }
    }
    

    当今几乎所有通用语言中的数组都是从索引开始的 0 [有关详细信息,请参阅 wiki .]循环数组 for (i = n; i >= 1; i--) 错误的是,由于heap是max,所以不要处理第一个元素,也不要处理最后一个元素。尽管使用 nth 元素是在标准中定义的,而不是这样 < n 和一些指针工作。

    在旁注中,您可以使用宏( #define s) 对于 left , right 以提高性能并简化阅读。

    我希望这能挽救一天 AlgoDat公司 运动