#include <iostream>
#include <vector>
using namespace std;
void HeapInsert(int *a,int index) //时间复杂度接近O(n),将其变成大根堆
{
while(a[index]>a[(index-1)/2])
{
swap(a[index],a[(index-1)/2]);
index=(index-1)/2;
}
}
void Heapify(int *a,int index,int n) //每次调整最顶端的,时间复杂度为logn
{
int left = index * 2 + 1;
while (left <= n)
{
int largest_index;
if(left+1 <= n && a[left+1] > a[left])
largest_index=left+1;
else
largest_index=left;
if(a[index] >= a[largest_index])
break;
else
{
swap(a[index], a[largest_index]);
index=largest_index;
left = index*2+1;
}
//int largest = left + 1 <= n && a[left + 1] > a[left] ? left + 1 : left;
//largest = a[largest] > a[index] ? largest : index;
//if (largest == index)
// break;
//swap(a[largest], a[index]);
//index = largest;
//left = index * 2 + 1;
}
}
void HeapSort(int *a,int n)
{
for(int i=0;i<n;i++)
HeapInsert(a,i); //大根堆
n--;
swap(a[0],a[n]);
n--; //传入最后一个位置的坐标
while(n>0)
{
Heapify(a,0,n);
swap(a[0],a[n]);
n--;
}
}
int main()
{
int a[]={1,0,3,4,2,1,5};
int n=sizeof(a)/sizeof(int);
for(int i=0;i<n;i++)
cout<<a[i]<<' ';
cout<<endl;
HeapSort(a,n);
for(int i=0;i<n;i++)
cout<<a[i]<<' ';
system("pause");
return 0;
}
堆排序
最新推荐文章于 2024-10-07 16:35:31 发布