1

我正在尝试将一个最大堆堆成一个最小堆。出于某种原因,我没有得到我期望的结果。

我已经建立了我的最大堆,它的数组内容按预期显示:

60 50 30 20 40 10

当尝试 heapfy 上述数组并将其转换为最小堆时,所需的结果是:

10 20 30 60 50 40

但是,我得到的结果是:

10 20 60 50 40 30

这是我的功能:

struct _heap
{
    int max; //array max
    int pos; //current position
    int* priority; //array gets initialized after.
};

typedef struct _heap heap_t;

void heapify_min(heap_t* h, int father)
{
    int smallest = father;
    int left = 2 * father + 1;
    int right = 2 * father + 2;

    if (left < h->pos && h->priority[left] < h->priority[smallest) {
        smallest = left;
    }
    if (dir < h->pos && h->priority[right] < h->priority[smallest])
        smallest = right;
    if (smallest != father) {
        swap(father,smallest,h->priority);
        heapify_min(h,left);
    }
}

void swap(int a, int b, int *v)
{
    int f = v[a];
    v[a] = v[b];
    v[b] = f;
}


void build_heap(heap_t* h)
{
    int n = h->pos;
    int i2 = (n/2) -1;
    int i;
    for (i = i2;i>=0;i--) {
        heapify_min(h,i);
    }
}


任何见解都会非常有帮助。

4

1 回答 1

0

根据我的代码检查您的代码(以下是 min_heap 的工作代码)。有3个问题:

  1. 在 heapify_min 函数中,当您递归调用函数时,您应该使用变量minimum not left

  2. 在 MIN HEAP 中比较值的运算符应该是 >(更大)而不是 <(更小)

  3. 函数 build_heap 是正确的,但这应该只是数组的第一次重新排列。在第一次重新排列数组(第一次创建最大堆)之后,您应该交换数组中的第一个和最后一个元素。在初始交换之后,您继续使用 heapify 函数,但每次进一步创建最大堆、交换子树中的值(在递归调用期间)以及将第一个元素与最后一个元素交换都是循环完成的,直到只剩下一个节点。

这是代码:

void heapify(int arr[], int n, int i)
{
    int smallest = i;
    int l = 2 * i + 1;
    int r = 2 * i + 2;

    // If left child is larger than root
    if (l < n && arr[l] > arr[smallest])
        smallest = l;

    // If right child is larger than largest so far
    if (r < n && arr[r] > arr[smallest])
       smallest = r;

    // If largest is not root
    if (smallest != i) {

        //swap
        int backUp = arr[i];
        arr[i] = arr[smallest];
        arr[smallest] = backUp;

        // Recursively call on heapify function
        heapify(arr, n, smallest);
     }
  }

  void heapSort(int arr[], int n)
  {
      // Build heap (rearrange array)
      for (int i = n / 2 - 1; i >= 0; i--)
         heapify(arr, n, i);

      // One by one extract an element from heap
      for (int i = n - 1; i > 0; i--) {

      // Swap root node with last node in array (WARNING: last node don't have to be 
     necessarily smallest one)
     int backUp = arr[0];
     arr[0] = arr[i];
     arr[i] = backUp;

     // call max heapify on the reduced heap
     heapify(arr, i, 0);
   }
}

    /* A utility function to print array of size n */
   void printArray(int arr[], int n)
   {
         for (int i = 0; i < n; ++i)
         printf("%d ", arr[i]);

         printf("\n");
   }
于 2021-05-22T11:22:32.607 回答