标签:arr int comp 堆排序 pos C++ size 模板 left
#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<<" " ;
}
}
标签:arr,int,comp,堆排序,pos,C++,size,模板,left 来源: https://www.cnblogs.com/daniel123/p/16376937.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。