题目:给一个数组进行堆排序
思路:
(1)将无序数组调整成大根堆,从最后一个非叶子结点开始,一直到根,调整时每次都按照一条路径一直到叶子结点
(2)将堆顶和待排序的最后一个元素进行交换,之后再调整堆,使之能够按照从小到大的顺序排列
代码:
#include <iostream>
using namespace std;
//堆排序,大根堆
void HeapAdjust(int* arr,int length,int location)
{
int nkey = arr[location];
int nChild = 0;
while (2*location+1 < length)
{
//孩子结点的位子
nChild = 2*location+1;
//找最大的孩子
if (nChild < length-1 && arr[nChild] < arr[nChild+1])
{
nChild++;
}
//最大孩子与父亲比较
if (arr[nChild] < nkey)
{
break;
}
arr[location] = arr[nChild];
location = nChild;//下一次调整location的位子
}
arr[location] = nkey;
}
void HeapSort(int* arr,int length)
{
//建成大顶堆
for (int i = (length/2)-1; i >=0; --i)
{
HeapAdjust(arr,length,i);
}
//排序,按照从小到大的顺序
for (int j = length-1; j >0; --j)
{
swap(arr[j],arr[0]);
HeapAdjust(arr,j,0);
}
}
int main()
{
int nlen;
cout<<"input array elem number:";
cin>>nlen;
int* arr = new int[nlen];
cout<<"input elem:"<<endl;
for (int i = 0; i < nlen; ++i)
{
cin>>arr[i];
}
HeapSort(arr,nlen);
delete[] arr;
arr = NULL;
}