使用了栈来避免递归,也解决了数据量大时爆栈的概率,代码:
void quik_sort(int v[],int l,int r){
std::stack <std::pair <int,int> > s;
s.push({l,r});
while (!s.empty()){
int L = s.top().first,R = s.top().second;
int i = L,j = R,flag = v[rand() % (R - L + 1) + L];
s.pop();
do{
while (v[i] < flag) i++;
while (v[j] > flag) j--;
if (i <= j)
std::swap(v[i],v[j]),i++,j--;
}while (i <= j);
if (L < j) s.push({L,j});
if (i < R) s.push({i,R});
}
}