标签:
堆排序(Heapsort)是指利用堆积树(堆)这种数据结构所设计的一种排序算法,它是选择排序的一种。可以利用数组的特点快速定位指定索引的元素。
堆分为大根堆和小根堆,是完全二叉树。大根堆的要求是每个节点的值都不大于其父节点的值,即A[PARENT[i]] >= A[i]。在数组的非降序排序中,需要使用的就是大根堆,因为根据大根堆的要求可知,最大的值一定在堆顶。
void max_heapify(vector<int>&A,int i)
{
int l=2*i+1,r=2*i+2,largest=0,temp;//l为第i个元素的左孩子,r为第i个元素的右孩子。
if(l<=A.size()-1&&A[l]>A[i])
largest=l;
else
largest=i;
if(r<=A.size()-1&&A[r]>A[largest])
largest=r;
if(largest!=i)
{
temp=A[i];
A[i]=A[largest];
A[largest]=temp;
max_heapify(A,largest);
}
}
void build_max_heap(vector<int>&A)
{
for(int i=A.size()/2-1;i>=0;i--)
{
max_heapify(A,i);
}
}
void heap_sort(vector<int>&A)
{
vector<int>B;
B=A;
int temp;
build_max_heap(B);
for(int i=B.size()-1;i>=1;i--)
{
temp=B[0];
B[0]=B[i];
B[i]=temp;
temp=B.back();
B.pop_back();
A[i]=temp;
max_heapify(B,0);
}
A[0]=B[0];
}#include<iostream> #include<vector> #include <stdlib.h> #include <time.h> using namespace std; void max_heapify(vector<int>&A,int i); void build_max_heap(vector<int>&A); void heap_sort(vector<int>&A);main.cpp
void build_max_heap(vector<int>&A)
{
for(int i=A.size()/2-1;i>=0;i--)
{
max_heapify(A,i);
}
}void heap_sort(vector<int>&A)
{
vector<int>B;
B=A;
int temp;
build_max_heap(B);
for(int i=B.size()-1;i>=1;i--)
{
temp=B[0];
B[0]=B[i];
B[i]=temp;
temp=B.back();
B.pop_back();
A[i]=temp;
max_heapify(B,0);
}
A[0]=B[0];
}void max_heapify(vector<int>&A,int i)
{
int l=2*i+1,r=2*i+2,largest=0,temp;
if(l<=A.size()-1&&A[l]>A[i])
largest=l;
else
largest=i;
if(r<=A.size()-1&&A[r]>A[largest])
largest=r;
if(largest!=i)
{
temp=A[i];
A[i]=A[largest];
A[largest]=temp;
max_heapify(A,largest);
}
}void main()
{
srand(time(NULL));
vector<int> str(11,0);
cout<<"str:"<<endl;
for(int i=0;i<str.size();i++)
{
str[i]=rand()%20;
cout<<str[i]<<" ";
}
cout<<endl;
heap_sort(str);
cout<<"After heap sort:"<<endl;
for(int i=0;i<str.size();i++)
{
cout<<str[i]<<" ";
}
cout<<endl;
}程序执行结果如下:
标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/45082743