1. 程式人生 > >經典內部排序: 堆排序,快排,歸併排序

經典內部排序: 堆排序,快排,歸併排序

堆排序:

#include <iostream>

using namespace std;

void minHeapFixDown(int a[],int i,int n){
    int tmp = a[i];
    int j = i*2+1;
    while(j<n){
        if(j+1<n&&a[j+1]<a[j])
            j++;
        if(a[i]<=a[j])
            break;
        swap(a[i],a[j]);
        i = j;
        j = i*2+1;
    }
}
void creatMinHeap(int a[],int n){
    for(int i=(n-1)/2;i>=0;i--){
        minHeapFixDown(a,i,n);
    }
}
int main()
{
    int a[10] = {0,8,3,7,5,1,4,6,2,9};
    //建立最小堆
    creatMinHeap(a,10);
    for(int i=0;i<10;i++)
        cout<<a[i]<<" ";
    cout<<endl;
    //每次交換堆頂和當前堆最後一個元素,最終陣列變為降序序列
    for(int i=9;i>=1;i--){
        swap(a[i],a[0]);
        minHeapFixDown(a,0,i);
    }
    for(int i=0;i<10;i++)
        cout<<a[i]<<" ";
    return 0;
}

快排:

#include <iostream>

using namespace std;

int partition(int a[],int left,int right){
    int tmp = a[right];
    int i = left-1;
    for(int j = left;j<right;j++){
        if(a[j]<=tmp){
            i++;
            if(i!=j)
                swap(a[i],a[j]);
        }
    }
    i++;
    swap(a[i],a[right]);
    return i;
}

void quickSort(int a[],int start,int end){
    if(a==NULL||start>end)
        return;
    int divot = partition(a,start,end);
    quickSort(a,start,divot-1);
    quickSort(a,divot+1,end);
}
int main()
{
    int a[10] = {0,8,3,7,5,1,4,6,2,9};
    quickSort(a,0,9);
    for(int i=0;i<10;i++)
        cout<<a[i]<<" ";
    return 0;
}

歸併排序:

#include <iostream>

using namespace std;
void mergeCoreSort(int a[],int start,int mid,int end){
        int p = mid-start+1;
        int q = end -mid;
        int left[p];
        int right[q];
        for(int i=0;i<p;i++)
            left[i] = a[start+i];
        for(int i=0;i<q;i++)
            right[i] = a[mid+i+1];
        int i=0;
        int j=0;
        int k=start;
        while(i<p&&j<q){
            if(left[i]<=right[j])
                a[k++] = left[i++];
            else
                a[k++] = right[j++];
        }
        while(i<p)
            a[k++] = left[i++];
        while(j<q)
            a[k++] = right[j++];
}

void mergeSort(int a[],int start,int end){
    if(start<end){
        int mid = (start+end)/2;
        mergeSort(a,start,mid);
        mergeSort(a,mid+1,end);
        mergeCoreSort(a,start,mid,end);
    }
}
int main()
{
    int a[10] = {0,8,3,7,5,1,4,6,2,9};
    mergeSort(a,0,9);
    for(int i=0;i<10;i++)
        cout<<a[i]<<" ";
    return 0;
}