#include<iostream>
#include<algorithm>
while(s<=end1){
if(( (s+1)<=end1)&&a[s]<a[s+1] )
s++;
if(a[f]>a[s])
return;
else{
swap(a[f], a[s]);
f=s;
s=2*f+1;
}
}
swap(a[0], a[i]); ///第一轮排序好 a[0]是最大元素 ,交换a[0]和a[len-1],此时最后一个元素是最大值 依次循环
make_maxheap(a,0,i-1);
}
}
int main() {
int ar[] = { 1,2,3,4,5,5,4,3,2,1 };
int len = (int) sizeof(ar) / sizeof(*ar);//计算数组的长度
heapSort(ar, len);
for (int j= 0; j < len; ++j)
cout << ar[j] << ' ';
return 0;
}
#include<algorithm>
using namespace std;
//构造大顶堆,时间复杂度O(logn)
void make_maxheap(int a[],int start,int end1){
int f=start;
int s=2*f+1;while(s<=end1){
if(( (s+1)<=end1)&&a[s]<a[s+1] )
s++;
if(a[f]>a[s])
return;
else{
swap(a[f], a[s]);
f=s;
s=2*f+1;
}
}
}
堆排序///
void heapSort(int a[],int len){
for(int i= len/2-1;i>=0;--i){
make_maxheap(a,i,len-1);
}
for( int i=len-1;i>0;i--){ ///交换第一个元素和排好序部分的前个元素swap(a[0], a[i]); ///第一轮排序好 a[0]是最大元素 ,交换a[0]和a[len-1],此时最后一个元素是最大值 依次循环
make_maxheap(a,0,i-1);
}
}
int main() {
int ar[] = { 1,2,3,4,5,5,4,3,2,1 };
int len = (int) sizeof(ar) / sizeof(*ar);//计算数组的长度
heapSort(ar, len);
for (int j= 0; j < len; ++j)
cout << ar[j] << ' ';
return 0;
}