c

时间:2019-03-17 11:33:27

标签: c algorithm heap minimum heapsort

你好,我陷入了编码算术运算的困境。请帮助我找到正确的数字。我使用的数字是:22,17,49,55,18,69,24,30,20,21。

用于最小化堆 我有:17,18,24,20,21,69,49,30,55,22

还要对堆进行排序, 我有:69,55,49,30,24,22,21,20,18,17

都是手工完成的。 代码的输出给了我错误的数字,我借用了代码并使用了它。 (感谢您与大家分享)

请帮助我这些人。.我一直在学习Java,并且刚刚开始上大学并学习C。

#include <stdio.h>

void main()
{ 
  int heap[10], no, i, j, c, root, temp;
  printf("\n Enter no of elements :");
  scanf_s("%d", &no);
  printf("\n Enter the input number : ");
  for (i = 0; i < no; i++)
    scanf_s("%d", &heap[i]);
  ///////////////////////////////////////////////////////////////////////////////////////
  printf("\n Your input number is : ");
  for (i = 0; i < no; i++)
    printf("%d\t ", heap[i]);
  //////////////////////////////////////////////////////////////////////////////////////
  for (i = 1; i < no; i++)
  {
    c = i;
    do
    {
      root = (c - 1) / 2;
      if (heap[root] < heap[c])   
      {
        temp = heap[root];
        heap[root] = heap[c];
        heap[c] = temp;
      }
      c = root;
    } while (c != 0);
  }
  printf("\n The makeHeap number is : ");
  for (i = 0; i < no; i++)
    printf("%d\t ", heap[i]);
  ////////////////////////////////////////////////////////////////////////////////////////
  for (j = no - 1; j >= 0; j--)
  {
    temp = heap[0];
    heap[0] = heap[j];    
    heap[j] = temp;
    root = 0;
    do
    {
      c = 2 * root + 1;    
      if ((heap[c] < heap[c + 1]) && c < j - 1)
        c++;
      if (heap[root] < heap[c] && c < j)   
      {
        temp = heap[root];
        heap[root] = heap[c];
        heap[c] = temp;
      }
      root = c;
    } while (c < j);
  }
  printf("\n The sorted number is : ");
  for (i = 0; i < no; i++)
    printf("%d\t", heap[i]);
  /////////////////////////////////////////////////////////////////////////////////////////
  printf("\n ");
  printf("\n ");
}

0 个答案:

没有答案
相关问题