您的位置:首页 > 编程语言 > C语言/C++

快速排序的C语言实现

2012-12-17 18:04 337 查看
#include <stdio.h>
#include <stdlib.h>

#define N 10

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

int main()
{
    int a
, 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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: