快速排序的C語言實現

#include <stdio.h>
#include <stdlib.h>

#define N 10

int split(int [], int, int);
void quickSort(int [], int, int);

int main()
{
    int a[N], i;
    //printf("Please Input %d Integers:\n", N);
    for(i=0; i<N; i++)
    {
        //scanf("%d", &a[i]);
        a[i] = rand();
    }
    printf("Before Sort, the arrary is: \n");
    for(i=0; i<N; i++)
    {
        printf("%d\t", a[i]);
    }

    quickSort(a, 0, N-1);

    printf("After Sort, the array is: \n");
    for(i=0; i<N; i++)
    {
        printf("%d\t", a[i]);
    }
    return 0;
}

int split(int a[], int low, int high)
{
    int partElement = a[low];

    for ( ; ; )
    {
        while(low<high && partElement<=a[high])
        {
            high--;
        }
        if (low>=high)
        {
            break;
        }
        a[low] = a[high];
        low++;


        while(low<high && a[low]<=partElement)
        {
            low++;
        }
        if(low>=high)
        {
            break;
        }
        a[high] = a[low];
        high--;
    }
    a[high] = partElement;
    return high;
}

void quickSort(int a[], int low, int high)
{
    int middle;
    if (low>=high)
    {
        return;
    }
    middle = split(a, low, high);
    quickSort(a, low, middle-1);
    quickSort(a, middle+1, high);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章