【问题标题】:Heap Sort giving wrong output堆排序给出错误的输出
【发布时间】:2016-06-28 09:08:02
【问题描述】:

苦苦思索堆排序算法,终于弄明白了,但还是不行,而且我似乎找不到问题,可能是因为我过去3个小时一直盯着它。 问题是它提供了错误的输入。该程序编译并没有给出错误。我使用了 Visual Studio 2013。 输入:{ 1, 4, 5, 3, 2, 7, 8, 5, 4, 7, 8, 1 } 预期输出:数组排序。

输出:1 2 3 5 7 1 4 4 7 8 5 8

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

void change(int *a, int *b){
    int aux;
    aux = *a;
    *a = *b;
    *b = aux;
}
void OrganizeHeap(int *A, int n, int i){
    int left = i * 2 + 1, right = i * 2 + 2;
    int largest = i;
    if (left < n && A[left] >= A[i])
        largest = left;

    if (right < n && A[right] >= A[i])
        largest = right;

    if (largest != i){
        change(&A[i], &A[largest]);
            OrganizeHeap(A, n, largest);
    }
}
void BuildHeap(int *A, int n){
    for (int i = n / 2 - 1; i >= 0; i--)
        OrganizeHeap(A, n, i);
}
void HeapSort(int *A, int n){
    BuildHeap(A, n);
    for (int i = n - 1; i >= 0; i--){
        change(&A[0], &A[i]);
        OrganizeHeap(A, i, 0);
    }
}
int main() {
    int max;
    int A[] = { 1, 4, 5, 3, 2, 7, 8, 5, 4, 7, 8, 1 };
    int n = sizeof(A) / sizeof(int);
    HeapSort(A, n);
    for (int i = 0; i < n; i++)
        printf("%d ", A[i]);
    _getch();
    return 0;
}

【问题讨论】:

  • 您需要包含预期输出和收到的输出。您还需要包含您的输入

标签: c algorithm sorting heapsort


【解决方案1】:

你的代码有两个问题

    if (right < n && A[right] >= A[i])
          largest = right;

如果A[i]5A[left]7 那么largest 将设置为left。 现在如果 A[right] 是 6.A[right] 大于 A[i] 那么最大将设置为 right.largest 应该是 left 而不是 right 因为 A[left] &gt; A[right] 所以你可以做类似的事情

  if (right < n && A[right] >= A[largest]) //see note below

第二个问题在编辑代码后已经解决了。

注意:

在检查时您可以只使用&gt; 而不是&gt;=

【讨论】:

  • 天啊...cant believe I didnt 看到了。谢谢!你刚刚救了我几个小时!确实,我发布了一个小问题,在编辑时看到它。再次感谢:)
猜你喜欢
  • 2014-02-13
  • 1970-01-01
  • 2017-09-02
  • 2015-06-06
  • 2020-09-08
  • 1970-01-01
  • 2016-01-19
  • 2018-01-13
  • 2017-01-27
相关资源
最近更新 更多