首页 > 编程语言 > 详细

堆排序

时间:2015-06-03 19:17:38      阅读:167      评论:0      收藏:0      [点我收藏+]
#include<iostream>
#include<vector>
using namespace std;

int  heapAdjust(int array[],int top,int depth)
{
     int rc=array[top];
     for(int i=top*2;i<=depth;i*=2)
     {
             if(i<depth && array[i]<array[i+1]&&(i+1)<=depth)
                 ++i;
             if(rc>array[i])
                 break;
             array[top]=array[i];
             top=i;
     }
     array[top]=rc;
}

void heapSort(int array[],int length)
{
     int i=0;
     for(i=length/2;i>0;--i)
     {
          heapAdjust(array,i,length);
     }
     for(i=length;i>1;--i)
     {
         int temp=array[1];
         array[1]=array[i];
         array[i]=temp;
         heapAdjust(array,1,i-1);
     }
}

int main()
{
   //第一次不算,因为是从下标1开始排序的。
   int a[9]={0,49,38,65,97,76,13,27,49};
   for(int i=0;i<9;i++)
   cout<<a[i]<<" ";
   cout<<endl;

   heapSort(a,8);
 //  heapAdjust(a,2,8);
   for(int i=0;i<9;i++)
   cout<<a[i]<<" ";
   cout<<endl;


  //  system("pause");
    return 0;
}

  

堆排序

原文:http://www.cnblogs.com/lxdonge/p/4549751.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!