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

2022/6/15 5:20:08

本文主要是介绍堆排序,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<<" " ;
}
}



这篇关于堆排序,C++,模板编程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程