快速排序

//快速排序算法
#include<iostream.h>
void sort(int start,int end,int *a)
{
    if (start>=end)  return;
    
    int low=start;
    int high=end;
    int x=a[start];
    int flag=0;
    while (low!=high)
    {
        if (flag==0)//左边空,从右向左找比x小的值
        {
            for(int j=high;j>=low;j--)
            {
                if (a[j]<x)
                {
                    a[low]=a[j];
                    flag=1;
                    high=j;
                    break;
                }
                else
                {
                    if(j==low)  high=low;
                }
            }
        } 
        else//右为空,从左向右找比x大的值
        {
            for (int j=low;j<=high;j++)
            {
                if (a[j]>x)//找到更改查找范围
                {
                    a[high]=a[j];
                    low=j;
                    flag=0;
                    break;
                }
                else
                {
                    if(j==high) low=high;//不存在,更改查找范围
                }
            }
        }
    }
    a[low]=x;
    sort(start,low-1,a);
    sort(low+1,end,a);
}
void main()
{
    int a[]={8,7,6,5,4,3,2,1};
    sort(0,7,a);
    for (int i=0;i<8;i++)
    {
        cout<<a[i]<<endl;
    }
}
原文地址:https://www.cnblogs.com/GoAhead/p/2672863.html