八种排序方法(四)——快速排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39360985/article/details/78813143

编译器:Xcode
编程语言:C++

源程序:

#include <iostream>
using namespace std;

int findPos(int a[],int low,int high)
{
    //将小于t的元素赶到t的左边,大于t的元素赶到t的右边
    int t=a[low];
    while(low<high)
    {
        while(low<high && a[high]>=t)
            high--;
        a[low]=a[high];
        while(low<high && a[low]<=t)
            low++;
        a[high]=a[low];
    }
    a[low]=t;
    //返回此时t在数组中的位置
    return low;
}

//在数组中找一个元素,对于大于该元素和小于该元素的两个数组进行再排序,
//再对两个数组分为4个数组,再排序,直到最后每组只剩下一个元素为止
void quickSort(int a[],int low,int high) //快速排序
{
    if(low>high)
        return ;
    int pos=findPos(a, low, high);
    quickSort(a, low, pos-1);
    quickSort(a, pos+1, high);
}

int main()
{
    int a[10] = {43, 65, 4, 23, 6, 98, 2, 65, 7, 79};
    cout<<"快速排序:"<<endl;
    quickSort(a, 0, 9);
    for(int i=0;i<10;i++)
        cout<<a[i]<<" ";
    cout<<endl;
    return 0;
}

运行结果:

快速排序:
2 4 6 7 23 43 65 65 79 98 
Program ended with exit code: 0

猜你喜欢

转载自blog.csdn.net/qq_39360985/article/details/78813143