c - 堆排序 : how to correct my coding and to implement my logic?

标签 c algorithm sorting

对于数组输入 2 5 8 3 4 6 我得到 2 4 5 3 8 6 我正在尝试实现堆排序,我是初学者,我不知道这里会出现什么错误,我只是想通过构建堆并将最后一个元素与最大的第一个索引交换来实现堆排序的逻辑元素,从而减小数组的大小。

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

构建一个获取起始索引中最高的元素

  heapify(int *a,int i,int no)
  {

      int largest = i;
      int left = 2*i;
      int right = 2*i+1;
      if(left<=no && a[left]>largest)
      {
        largest=left;
      }

      if(right<=no && a[right]>largest)
      {
          largest=right;
      }

      if(largest!=i)
      {
          int temp=a[largest];      
          a[largest]=a[i];
          a[i]=temp;
          heapify(a,largest,no);
      }
  }

对数组中的元素进行堆排序

  heapsort(int *a,int no)
  {
      while(no>1)
      {
          int temp=a[1];
          a[1]=a[no];
          a[no]=temp;
          --no;
          heapify(a,1,no);
      }
  }

打印数组中的元素

  printarr(int *a,int no)
  {
      int i=1;

      for(;i<=no;i++)
          printf("%d",a[i]);      
  }

这是主要功能。

  int main()
  {
      int i,j,k,no,size;

      printf("Enter the no of elements");
      scanf("%d",&no);
      int a[no+1];
      size=no;

      for(i=1;i<=no;i++)
      {
        scanf("%d",&a[i]);
      }

      printarr(a,no);
      j=no/2;

      for(i=j;i>0;--i)
      {
        heapify(a,i,no);
      }

      heapsort(a,no);
      printarr(a,no);

      getch();

      return 0;
  }

最佳答案

你在 heapify 函数中比较索引和数组值

 if(left<=no && a[left]>largest)

if(right<=no && a[right]>largest)

应该是

 if(left<=no && a[left]>a[largest])

if(right<=no && a[right]>a[largest])

关于c - 堆排序 : how to correct my coding and to implement my logic?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25378032/

相关文章:

javascript - 根据 Javascript 中的条件过滤、排序和映射数组

c - LPC17xx : Check if RTC is running

c - (void) 'variable name' 在 C 函数的开头做什么?

c - 为什么指针值会改变?

python - 具有重复元素的简单选择排序?

mysql - 插入已排序的 SQL 条目

c - 在用作 SQLite 聚合器的 C 函数中初始化结构中的值

algorithm - 如何确定哪些边是顶点子集之间的简单路径的一部分?

algorithm - 数组中的二进制搜索

algorithm - 当任何两个元素之间的比较可能不明确时对列表进行排序?