数据结构之快速排序

来源:互联网 发布:淘宝买机票 编辑:程序博客网 时间:2024/06/06 08:28
#include<iostream>
using namespace std;
int a[10000];
int partition(int a[],int low,int high)
{
    int temp=a[low];//记录子表的第一个元素的值为枢值
    while(low<high)//从表的两端交替地向中间扫描
    {
        while((low<high)&&(a[high]>=temp))//将比枢值小的移到低端
            --high;
            a[low]=a[high];
        while((low<high)&&(a[low]<=temp))//将比字表枢值大的移到高端
            ++low;
            a[high]=a[low];
    }
    a[low]=temp;
    return low;//返回最后枢值所在的下标
}
void  Quicksort(int a[],int low,int high)
{//对顺序表中的子序列做快排
    if(low<high)
    {
         int temp=partition(a,low,high);//将子表一分为二
         //cout<<temp<<endl;
        Quicksort(a,low,temp-1);//对低子表进行递归排序
        Quicksort(a,temp+1,high);//对高子表进行递归排序
    }
}


int main()
{


    cout<<"输入元素个数:";
    int n;
    cin>>n;
    cout<<"输入"<<n<<"个元素;";
    for(int i=0;i<n;i++)
        cin>>a[i];
        Quicksort(a,0,n-1);
        for(int i=0;i<n;i++)
        cout<<a[i]<<" ";


    return 0;
}
原创粉丝点击