快速排序

时间复杂度为nlogn,最坏 n^2

一个递归的问题。

/* ***********************************************
Author        :pk28
Created Time  :2015/11/13 20:24:14
File Name     :2.cpp
************************************************ */
#include <iostream>
#include <vector>
using namespace std;

void quicksort(vector<int>&v,int l,int r){
    if(r<=l)return ;
    int k=v[l];//mid
    int low=l;
    int high=r;
    while(low<high){//移动指针
        while(low<high&&v[high]>k)high--;
        while(low<high&&v[low]<k)low++;
        swap(v[low],v[high]);
    }
    quicksort(v,l,low-1);
    quicksort(v,low+1,r);

}
int main()
{
    int n;
    while(cin>>n){
        int x;
        vector<int>v;
        for(int i=0;i<n;i++){
            cin>>x;
            v.push_back(x);
        }
        quicksort(v,0,n-1);
        for(int i=0;i<n;i++){
            cout<<v[i]<<" ";
        }
        cout<<endl;
    }
    return 0;
}

 

posted on 2015-11-13 21:03  Beserious  阅读(200)  评论(0编辑  收藏  举报