//大根堆
# include <iostream>
using namespace std;
void swap(int *a,int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void print_arr(int *arr,int n)
{
for(int i=1;i<=n;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
//对一个节点及其子节点进行排序、交换
void heapify(int *arr,int n,int i)
{
int largest = i;
int left_child = 2*i;
int right_child = 2*i + 1;
if(left_child <= n && arr[largest] > arr[left_child]){
largest = left_child;
}
if(right_child <= n && arr[largest] > arr[right_child]){
largest = right_child;
}
if(largest != i){
swap(&arr[i],&arr[largest]);
heapify(arr,n,largest);
}
}
void heap_sort(int *arr,int n)
{
//初始建堆
int i;
for(i=n/2;i>0;i--)
heapify(arr,n,i);
//每一次建堆完要交换一下次序
//再进行下一次建堆
for(i=n;i>1;i--)
{
swap(&arr[i],&arr[1]);
heapify(arr,i-1,1);
}
}
int main()
{
int arr[11]={0,43,74,1,6,3,2,96,23,10,25};
heap_sort(arr,10);
print_arr(arr,10);
return 0;
}
C++ 大根堆 建立 数据结构
最新推荐文章于 2024-07-31 17:27:42 发布