堆排序 C++

#include<iostream>

using namespace std;

//调整堆
void adjust_heap(int *arr,int size,int pos){
int left = pos*2 +1;
int right = pos*2 + 2;

//左右两边先选取最小的,如果大于最小的,那么跟最小的交换位置。
if(right < size){
left = (arr[left] < arr[right]) ? left : right;
}
if(left < size && arr[pos] > arr[left]){
int tmp = arr[left];
arr[left] = arr[pos];
arr[pos] = tmp;
adjust_heap(arr,size, left);
}
}

// 堆排序
void heap_sort(int* arr,int size){
//建堆
for(int pos = size -1 ;pos > 0;pos--){
if(arr[pos] < arr[(pos-1)/2]) {
int tmp = arr[pos];
arr[pos] = arr[(pos-1)/2];
arr[(pos-1)/2] = tmp;
}
adjust_heap(arr,size,pos);
}
//交换首尾,再次调整

for(int pos = size -1;pos > 0;pos--){
int tmp = arr[0];
arr[0] = arr[pos];
arr[pos] = tmp;
adjust_heap(arr,pos,0);
}
}

int main()
{
int arr[11] = {0,3,5,8,1,2,10,7,8,9,2};
heap_sort(arr,11);

for(auto it : arr)
{
cout<<it<<" " ;
}
}

posted @ 2022-06-12 22:36  danieldai  阅读(23)  评论(0编辑  收藏  举报