快速排序(QuickSort)

快速排序(QuickSort)
快速排序(QuickSort)
快速排序(QuickSort)
快速排序(QuickSort)
快速排序(QuickSort)
快速排序(QuickSort)
具体实现代码如下:


//QuickSort
#include <iostream>
#include <stdio.h>

int Partition(int a[], int L, int R){
    int p=a[L];//中轴
    int i=L+1,j=R;
    while(1){
        while(a[i]<p && i<=R)i++;
        while(a[j]>p && j>=L)j--;
        if(i>=j)break;
        std::swap(a[i],a[j]);
    }
    std::swap(a[L],a[j]);
    return j;
}

void QuickSort(int a[], int L, int R){
    if(L<R){
        int k=Partition(a,L,R);
        QuickSort(a,L,k-1);
        QuickSort(a,k+1,R);
    }
}

int main()
{
    int n;
    while(scanf("%d",&n)!=EOF){
        int a[n];
        for(int i=0;i<n;i++){
            scanf("%d",&a[i]);
        }

        QuickSort(a,0,n-1);

        for(int i=0;i<n;i++){
            printf("%d ",a[i]);
        }
        printf("\n");
    }
    return 0;
}

相关文章: