现在的位置: 首页 > 综合 > 正文

快速排序C++实现

2014年01月04日 ⁄ 综合 ⁄ 共 586字 ⁄ 字号 评论关闭
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int part(int a[],int low,int high);
void sort(int *a,int low,int high);
int main()
{
    int a[]={6,31,25,10,5,35,26,3,2,8,9,11,4,45,48};
    sort(a,0,14);
    for(i=0;i<14;i++)
        printf("%d ",a[i]);
    return 0;
}

int part(int a[],int low,int high)
{
    int temp=a[low]; //等于a[low]
    while(low<high)
    {
        while(low<high&&a[high]>=temp) 
            --high;
        a[low]=a[high];
        while(low<high&&a[low]<=temp) 
            ++low;                            //while(low<high&&a[low<=temp]) ++low;错误地方
        a[high]=a[low];
    }
    a[low]=temp;
    return low;
}

void sort(int a[],int low,int high)
{
    int loc=0;
    if(low<high)
    {
        int loc=part(a,low,high);
        sort(a,low,loc-1);
        sort(a,loc+1,high);
    }
}

 

抱歉!评论已关闭.