毕业一年多后在写快速排序

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void print(int elem)
{
    cout<<elem<<" ";
}

void quicksort(vector<int> &vec, int left, int right)
{
        if(left < right)
        {
            int key = vec[left];
            int low = left;
            int high = right;
            while(low < high)
            {
                while(low < high && vec[high] > key)
                {
                    high--;
                }
                vec[low] = vec[high];

                while(low < high && vec[low] < key)
                {
                    low++;
                }
                vec[high] = vec[low];
            }
            vec[low] = key;
            quicksort(vec, left, low-1);
            quicksort(vec, low+1, right);
        }


}


int main()
{
    int arr[10] = {10,8,2,3,5,7,6,9,4,1};
    vector<int> vec(arr, arr+10);
    cout<<"before quicksort:";
    for_each(vec.begin(), vec.end(), print);
    cout<<endl;
    int left = 0;
    int right = vec.size();
    quicksort(vec, left, right);
    cout<<"after quicksort:";
    for_each(vec.begin(), vec.end(), print);
    cout<<endl;
    return 0;
}

 

posted @ 2017-01-14 20:45  xshang  阅读(173)  评论(0编辑  收藏  举报