快速排序

落爺英雄遲暮 提交于 2019-12-15 19:59:15
#include <stdio.h>
void input(int[], int n);//输入函数
void output(int[], int n);//输出函数
void quicksort(int[], int low, int high);//快排调用函数
int split(int a[], int low, int high);//分割排序函数
int main()//10        5 8 9 2 1 10 6 4 3 7  测试数据
{
    int a[10];
    int n;
    scanf("%d", &n);
    input(a, n);
    quicksort(a, 0, n - 1);//传a的起始下标和最终下标
    output(a, n);
    return 0;
}
void input(int a[], int n)
{
    for (int i = 0; i < n; i++)
        scanf("%d", &a[i]);
}
void output(int a[], int n)
{
    for (int i = 0; i < n; i++)
        printf("%d ", a[i]);
}

void quicksort(int a[], int low, int high)
{
    int mid;
    if (low >= high)//有了等号效率会高
        return;
    mid = split(a, low, high);  //每次的中间(左面是小与中间变量的,
    //右面是大于的)变量的地,每次递推都把那个确定的范围再分成两个确定的范围,直到一个数无数可分
    //再 回溯 一个接一个的
    quicksort(a, low, mid - 1);
    quicksort(a, mid + 1, high);
}
int split(int a[], int low, int high)
{
    int p = a[low];
    while (1)//靠内层退出
    {
        while (low < high && p <= a[high])//不能有等号,因为有了的话low左面的一项也会和p比较
            high--;                       //或者说是high右面的一项也会和p比较,就是会多比较一项,多移一个数(不合适于该p条件的数)
        if (low >= high)//必须有等号  //这个时候,上次循环之后low和high已经相等了。也就不能再执行了
            break;
        a[low++] = a[high];//a[low]也可以,但这样效率会更高,可以把倒数第二行的注释解开 试试
        while (low < high && p >= a[low])
            low++;
        if (low >= high)
            break;
        a[high--] = a[low];//a[high] 同理
    }
    a[low]=p;   //这里low和high 都可以,因为最后他们是相等的
   // printf("%d %d\n",low,high);//测试用
    return low;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!