background image

cout<<endl;

    quick_sort(0,9);

cout<<"After sorted:\t";

    for(i=0;i<10;i++)
        cout<<a[i]<<"  ";

cout<<endl;

}

2、运行结果

Before sorting: 7  5  7  9  4  10  21  -5  -2  32  
After sorted: -5  -2  4  5  7  7  9  10  21  32  

堆排序

1、程序代码

#include <iostream>  
using namespace std ;
//

 

生成大根堆

void HeapAdjust(int SortData[],int StartIndex, int Length) {   
   while(2*StartIndex+1 < Length) {   
      int MinChildrenIndex = 2*StartIndex+1 ;   
      if(2*StartIndex+2 < Length )   {   
         //比较左子树和右子树,记录最大值的 Index   
      if(SortData[2*StartIndex+1]<SortData[2*StartIndex+2]){   
              MinChildrenIndex = 2*StartIndex+2;   
            }   
        }   
      if(SortData[StartIndex] < SortData[MinChildrenIndex])  {   
          //交换 i 与 MinChildrenIndex

  

的数据

          int tmpData =SortData[StartIndex];   
           SortData[StartIndex] =SortData[MinChildrenIndex];   
          SortData[MinChildrenIndex] =tmpData;   
            //

   

堆被破坏,需要重新调整

            StartIndex = MinChildrenIndex ;   
       }    else      {   
           //

               

比较左右孩子均大则堆未破坏,不再需要调整

break;        

}   

    }   
  
    return;   
}   
  
//

   

堆排序

void HeapSortData(int SortData[], int Length)  {   
  int i=0;   
   //将 Hr[0,Lenght-1]

   

建成大根堆