堆排序,网上还弄了些不错的网站,下面推荐一个:
- #include <iostream>
- #include <stdlib.h>
- #include <time.h>
- using namespace std;
- int g_nCases = 0;
- template<typename T>
- void shitHeap(T array[], int const nIndex, int const nSize)
- {
- T tempData = array[nIndex];
- // left child
- int nChild = nIndex *2;
- while(nChild <nSize){
- if(array[nChild]<array[nChild+1]){
- nChild++;
- }
- if(tempData >=array[nChild])
- break;
- // 大者上移
- array[nChild/2] = array[nChild];
- nChild *= 2;
- }
- array[nChild/2] = tempData;
- }
- template<typename T>
- void heapSort(T array[], int const n)
- {
- // make a heap
- // 从最后一个分支节点开始
- for(int m = n/2; m>=0; m--){
- shitHeap(array, m, n);
- }
- // out--让大的放到后面去
- for(int m = n-1; m>=0; m--){
- swap(array[0], array[m]);
- shitHeap(array, 0, m-1);
- }
- }
- template<class T>
- void printArray(T array[], int const n)
- {
- cout<<"Case "<<g_nCases++<<" :"<<endl;
- for(int i=0; i<n; i++)
- cout<<array[i]<<", ";
- cout<<endl;
- }
- int main(int argc, char *argv[])
- {
- srand((unsigned)time(NULL));
- const int N = 1000;
- int array[N];
- // Init
- for(int i=0; i<N; i++){
- array[i] = rand()%N;
- }
- printArray(array, N);
- heapSort(array,N);
- printArray(array, N);
- return 0;
- }