天天看點

八種排序方法(六)——堆排序

編譯器:Xcode

程式設計語言:C++

源程式:

#include <iostream>
using namespace std;

void swap(int a[],int i,int j) //交換函數
{
    int temp;
    temp=a[i];
    a[i]=a[j];
    a[j]=temp;
}

void heapAdjust(int a[],int i,int n)
{
    int temp;
    //假設第一個結點的元素是最大的
    temp=a[i];
    //i結點:2*i是i結點的左結點,2*i+1是結點的右結點
    //把結點元素大的交換到前面
    for(int j=*i;j<=n;j*=)
    {
        if(j<n && a[j]<a[j+])
            j++;
        if(temp>=a[j])
            break;
        a[i]=a[j];
        i=j;
    }
    a[i]=temp;
}

//堆排序将數組先組成二叉樹,預設從數組的a[1]開始排,a[0]是無效資料
void heapSort(int a[],int n) //堆排序
{
    int i;
    //先将數組組成一棵完全二叉樹
    //從2/n開始,就是從倒數第二排結點往前開始
    for(int i=n/;i>;i--)
    {
        heapAdjust(a, i, n);
    }
    //循環每個結點,将大的結點交換到堆頂
    for(i=n;i>;i--)
    {
        swap(a,,i);
        //每次交換完都要調整二叉樹,将剩下的最大結點交換到堆頂
        heapAdjust(a, , i-);
    }
}

int main()
{
    int a[] = {-,, , , , , , , , , };
    cout<<"堆排序:"<<endl;
    heapSort(a, );
    for(int i=;i<;i++)
        cout<<a[i]<<" ";
    cout<<endl;
    return ;
}
           

運作結果:

堆排序:
          
Program ended with exit code: 
           

繼續閱讀