快排

#include<iostream>
using namespace std;

void quick_sort(int array[], int start, int end)
{
    if(start>=end) return; //递归终止条件
    int i = start;
    int j = end;
    int temp = array[i];

    while (i < j)
    {
        while (i < j && array[j]>=temp )
        {
            j--;
        }
        array[i] = array[j];

        while (i < j && array[i]<temp)
        {
            i++;
        }
        array[j] = array[i];
    }
    array[i] = temp;//此时i==j,把基准数放到i位置

    quick_sort(array, start, i - 1);
    quick_sort(array, i + 1, end);
}

int main()
{
    int array[]= {21,25,49,25,16,8};
    int len=sizeof(array)/sizeof(int);
    cout<<"The orginal array are:"<<endl;
    for(int i=0; i<len; i++)
    {
        cout<< array[i] << " ";
    }
    cout<<endl;
    quick_sort(array,0,len-1);
    cout<<"The sorted array are:"<<endl;
    for(int i=0; i<len; i++)
    {
        cout<< array[i] << " ";
    }
    cout<<endl;
    return 0;
}

 

posted @ 2020-07-28 17:57  执着于风  Views(173)  Comments(0)    收藏  举报