c语言 快速排序 代码

Modified on: Sat, 16 Mar 2019 17:06:43 +0800 热度: 813 度
#include <stdio.h>
void quicksort (int arr[],int L,int R,int Direction);

int arr[]={4,2,9,8,5,6,1,3,7,3};

int main(int argc, const char * argv[]) {
    int i;
    int len=(int)sizeof(arr)/sizeof(arr[0]);
    for(i=0;i<len;i++)
    {
        printf("%d ",arr[i]);
    }
    putchar(10);
    quicksort(arr, 0, len-1,0);
    for(i=0;i<len;i++)
    {
        printf("%d ",arr[i]);
    }
    putchar(10);
    quicksort(arr, 0, len-1,1);
    for(i=0;i<len;i++)
    {
        printf("%d ",arr[i]);
    }
    putchar(10);
    return 0;
}
void quicksort (int arr[],int L,int R,int Direction)
{
    int i = L;
    int j = R;
    int pivot =arr[(L+R)/2];
    while(i<=j)
    {
        while(Direction? arr[i] > pivot:arr[i] < pivot)
        {
            i++;
        }
        while(Direction? arr[j] < pivot:arr[j] > pivot)
        {
            j--;
        }
        if(i<=j)
        {
            int temp= arr[i];
            arr[i]= arr[j];
            arr[j]= temp;
            i++;
            j--;
        }
    }

    if(L<j)
    {
        quicksort(arr ,L ,j,Direction);
    }
    if(i<R)
    {
        quicksort(arr ,i ,R,Direction);
    }
}

添加新评论