堆排序

#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;
}

  

posted @ 2015-06-03 17:28  lxdonge  阅读(177)  评论(0)    收藏  举报