堆排序(选择排序的一种)

https://www.cnblogs.com/MOBIN/p/5374217.html

https://www.cnblogs.com/chengxiao/p/6194356.html

堆排序是一种选择排序,它的最坏,最好,平均时间复杂度均为O(nlogn),它是不稳定排序。

一般升序采用大顶堆,降序采用小顶堆。

 1 //HeapSort堆排序
 2 void Swap(int a[], int i, int j)
 3 {
 4     int temp = a[i];
 5     a[i] = a[j];
 6     a[j] = temp;
 7 }
 8 
 9 void AdjustHeap(int a[], int i, int index)   //调整为大顶堆:升序使用大顶堆,降序使用小顶堆
10 {
11     int left, right, j;
12     while ((left = 2*i+1) <= index)
13     {
14         right = left + 1;
15         j = left;
16         if (j < index && a[left] < a[right])
17         {
18             j++;
19         }
20         if (a[i] < a[j])
21         {
22             Swap(a, i, j);
23             i = j;  //如果进行了交换,需要再重新对该非叶子节点及其儿子进行调整
24         }
25         else
26         {
27             break;
28         }
29     }
30 }
31 
32 void HeapSort(int a[], int len)
33 {
34     int index = len -1;
35     int i = index / 2 -1;
36     for (; i >= 0; i--)
37     {
38         AdjustHeap(a, i, index);
39     }
40 
41     while (index > 0)
42     {
43         Swap(a, 0, index--);
44         AdjustHeap(a, 0, index);
45     }
46 }

测试:

 1 int _tmain(int argc, _TCHAR* argv[])
 2 {
 3     int a[7] = {5,3,7,4,8,1,10};
 4     //QuickSort2(a, 0, 6);
 5     //BubbleSort(a, 7);
 6     HeapSort(a, 7);
 7     for (int i = 0; i < 7; i++)
 8     {
 9         printf("%4d", a[i]);
10     }
11     return 0;
12 }

 排序算法总结:https://www.cnblogs.com/RainyBear/p/5258483.html

 

转载于:https://www.cnblogs.com/cinvzi/p/9394039.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值