#include <iostream>
#include <time.h>
using namespace std;
/*
快速排序
a:待排数组
left:待排数组元素的起始下标
right:待排数组最后一个元素下标
*/
template<class T>
void quickSort(T *a,int left,int right){
if(left>=right)
return;
int l=left,r=right;
T pivot=a[left];
while(l<r){
while(l<r&&a[r]>=pivot)r--;
a[l]=a[r];
while(l<r&&a[l]<=pivot)l++;
a[r]=a[l];
}
a[l]=pivot;
quickSort(a,left,l-1);
quickSort(a,l+1,right);
}
void quickSortForString(string &a,int left,int right){
if(left>=right)
return;
int l=left,r=right;
int pivot=a[left];
while(l<r){
while(l<r&&a[r]>=pivot)r--;
a[l]=a[r];
while(l<r&&a[l]<=pivot)l++;
a[r]=a[l];
}
a[l]=pivot;
quickSortForString(a,left,l-1);
quickSortForString(a,l+1,right);
}
/*
打印数组的内容
a:待打印数组
s:待打印数组中欲打印的起始元素下标
e:待打印数组中欲打印的最后一个元素下标
lineCount:一行打印多少个
*/
template<class T>
void print(T *a,int s,int e,int lineCount){
for(int i=s;i<=e;++i){
cout<<a[i]<<" ";
if((i-s+1)%lineCount==0&&!i==e)
cout<<endl;
}
}
int main(int argc,char *argv[]){
time_t tStart,tEnd;
tStart=clock();
string str="hello world";
cout<<str.c_str()<<endl;
quickSortForString(str,0,str.size()-1);
cout<<str.c_str()<<endl;
const int N=10;
int a[N];
srand(time(NULL));
for(int i=0;i<N;i++)
a[i]=rand()%10;
print(a,0,N-1,N);
cout<<endl;
quickSort(a,0,N-1);
print(a,0,N-1,N);
cout<<endl;
tEnd=clock();
cout<<"time consumer: "<<difftime(tEnd,tStart)<<endl;
getchar();
return 0;
}