快速排序(N.Lomuto版)

来源:互联网 发布:花千骨网络视频 编辑:程序博客网 时间:2024/05/16 01:43

这个版本的快速排序是由N.Lomuto提出来的。

基本排序步骤如下图所示:



/* *  名   称:  快速排序 *  作   者: Brooke gao *  日   期: 2013/6/17 * */#include <stdio.h>#define SIZE 100void swap(int *x, int *y){    int temp;    temp = *x;    *x = *y;    *y = temp;}int Partition(int *A, int p, int r){    int x, i, j;    x = A[r];    i = p - 1;        for(j = p; j <= r - 1; j++)    {        if(A[j] <= x)        {            i++;            swap(&A[i],&A[j]);        }    }    swap(&A[i+1],&A[r]);    return i+1;}void QuickSort(int *A, int p, int r){int q;if(p < r){q = Partition(A,p,r);QuickSort(A,p,q-1);QuickSort(A,q+1,r);}}void PrintResult(int *A, int size){int i;    for(i = 0; i < size; i++)    {        printf("%-2d",A[i]);    }    putchar('\n');}int main(void){    int i, sum;    int A[SIZE];    printf("输入需排序的元素个数(0-100): ");    scanf("%d",&sum);    printf("请输入%d个元素:\n",sum);    for(i = 0; i < sum; i++)    {scanf("%d",&A[i]);    }    QuickSort(A,0,sum-1);    printf("排序结果:\n");    PrintResult(A,sum);}

原创粉丝点击