堆排序,C++,模板编程

#include<iostream>

using namespace std;

template<typename T>

struct comp_function{
bool operator()(const T &lhs,const T &rhs){
return lhs<rhs;
}
};   //比较大小的方法

comp_function<int> comp_a;

// 调整堆

template<typename T>
void adjust_heap(T *arr,int size,int pos,comp_function<T> comp_f){
int left = pos*2 + 1;
int right = pos*2 + 2;
if(right < size){
left = comp_f(arr[left],arr[right]) ? left : right;
// left = (arr[left] < arr[right]) ? left : right;
}
if(left<size && comp_f(arr[left],arr[pos])){
T tmp = arr[left];
arr[left] = arr[pos];
arr[pos] = tmp;
adjust_heap(arr,size,left,comp_a);
}
}

// 堆排序主体,建堆,调整堆。

template<typename T>
void heap_sort(T* arr,int size,comp_function<T> comp_f){
for(int pos = size-1 ; pos > 0; pos--){
if(comp_f(arr[pos],arr[(pos-1)/2])){
T tmp = arr[pos];
arr[pos] = arr[(pos-1)/2];
arr[(pos-1)/2] = tmp;
}
adjust_heap(arr,size,pos,comp_f);
}
for(int pos = size-1; pos > 0;pos--){
T tmp = arr[0];
arr[0] = arr[pos];
arr[pos] = tmp;
adjust_heap(arr,pos,0,comp_f);
}
}

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

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

posted @ 2022-06-15 00:21  danieldai  阅读(29)  评论(0编辑  收藏  举报