C++快排

#include <iostream>
#include <memory>
using namespace std;

void print(int *a,int len){
    for(int i=0;i<len;i++){
        cout<<a[i]<<" ";
    }
    cout<<endl;
}

void qs(int *a,int low, int high){
    int left= low;
    int right = high;
    int pivot = a[left];
    if(left>=right) return;  //结束条件,不然会死循环
    while(left<right){
        while(left<right){
           if(a[right--]<pivot){
               a[left] = a[++right];
//               print(a,5);
               break;
           }
        }
        while(left<right){
            if(a[left++]>pivot){
                a[right]=a[--left];
//                print(a,5);
                break;
            }
        }

    }
    a[left] = pivot;
    qs(a,low,left-1);
    qs(a,left+1,high);
}
int main() {
    {
        int a[5]={3,1,5,2,4};
        qs(a,0,4);
        print(a,5);
    }
}

猜你喜欢

转载自www.cnblogs.com/whalelife/p/10747956.html