对vector<int>进行快速排序

#include <iostream>
#include <string>
#include <vector>
using namespace std;
void QuickSort_danny();
void QSort(vector<int>& ivec, vector<int>::iterator low,vector<int>::iterator high);

 

void QuickSort_danny()
{
int input;
vector<int> ivec;
while(cin>>input)
{
ivec.push_back(input);
}
for (vector<int>::iterator iter=ivec.begin(); iter!=ivec.end(); iter++)
{
cout << *iter << " ";
}

QSort(ivec,ivec.begin(),ivec.end()-1);

cout <<endl;
for (vector<int>::iterator iter=ivec.begin(); iter!=ivec.end(); iter++)
{
cout << *iter << " ";
}
}

vector<int>::iterator Partition(vector<int>&, vector<int>::iterator low,vector<int>::iterator high)
{
vector<int>::value_type pivokey = *low;
while(low<high)
{
while(low < high && *high > pivokey ) high--; // 若此处为 *high >= pivokey; 则对于5 8 5,进行快速排序仍然为 5 8 5, 不能将
// 序列变为 5 5 8. 且最后high和low均为第一个元素,故QSort中iter-1会出现越界错误;
*low = *high;
while(low < high && *low <= pivokey) low++;
*high =*low;
}
*low = pivokey;
return low;
}

void QSort(vector<int>& ivec, vector<int>::iterator low,vector<int>::iterator high)
{
if (low < high)
{
vector<int>::iterator iter = Partition(ivec, low, high);
QSort(ivec, low, iter-1);
QSort(ivec, iter+1, high);
}
}

 

posted on 2014-04-11 21:31  Danny王  阅读(2385)  评论(0编辑  收藏  举报

导航