天天看點

C++ 快排

//把最後一個當主元 piovt 
    int small = s;
    int pivot = a[e];
    int i = s, j = e ;
    while( i < j){
        if(a[i] >= pivot){
            i++;
        }else{
            swap(a[small],a[i]);
            i++;
            ++small;
        }
    }
    swap(a[small],a[e]);
    return small;
           
int temp = a[s];
    int i = s, j = e;
    while(i < j ){
        while(a[j]>= temp && i < j){
            j--;
        }
        if(i<j)
            a[i++] = a[j];
        while(a[i]<temp && i < j){
            i++;
        }
        if(i<j)
            a[j--] = a[i];
    }
    a[i] = temp;
    return i;
           

快排的多重實作方式

#include <iostream>
using namespace std;
/*快排*/ 
int quick(int a[], int s, int e)
{
    //上面兩種都可以.
}
void quicksort(int a[], int s, int e)
{
    if(s < e)
    {
        int i = quick(a,s,e);
        quicksort(a,s,i-);
        quicksort(a,i+,e);
    }
}
int main()
{
    int a[] = {-,,,,,,,}; // 8 elements;
    int s = , e = ;
    quicksort(a,s,e);
    for( int i =  ;i <= e;i++)
        cout<<a[i]<<" ";
    cout<<endl;
}
           

繼續閱讀