您的位置:首页 > 其它

堆排序

2015-06-03 17:28 288 查看
#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;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: