堆排序

堆排序是O(N*logN),经验中它是一个稳定的排序算法,实际中慢于希尔排序。

 

#include "stdafx.h"
#include "stdio.h"

#define  LeftChild( i ) ( 2 * ( i ) + 1)

void Swap(int* a1, int* a2)
{
 int temp = *a1;
 *a1 = *a2;
 *a2 = temp;
}

void PercDown(int A[], int i, int count)
{
 int child;
 int temp;

 for( temp = A[i]; LeftChild(i) < count; i = child )
 {
  //左儿子
  child = LeftChild(i);
  //没有到最末尾,右儿子大于左儿子,则指向右儿子
  if( child != count - 1 && A[child+1] > A[child] )
   child++;
  if( temp < A[child] )//如果小于儿子,则儿子上浮
   A[i] = A[child];
  else
   break;//大于儿子则放入堆中
 }
 A[i] = temp;//数据进入堆中
}

void HeapSort(int A[], int count)
{
 int i;

 //建立一个堆
 for( i = count / 2; i >= 0; i-- )
 {
  PercDown(A, i, count);//插入到堆中
  for( int j = 0; j < count; j++ )
   printf("%d  ", A[j]);
  printf("/n");
 }

 for( i = count - 1; i > 0; i-- )
 {
  //下标0为最大值,放置到数组末尾,然后将下标0插入到堆中
  Swap( &A[0], &A[i] );
  PercDown(A, 0, i);
 }
}

int _tmain(int argc, _TCHAR* argv[])
{
 int A[] = { 12, 45, 98, 68, 37, 6, 21, 88};
 int count = sizeof(A) / sizeof(A[0]);

 HeapSort(A, count);

 for( int i = 0; i < count; i++ )
  printf("%d  ", A[i]);

 return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值