Last active
August 29, 2015 14:07
-
-
Save libratiger/82fed2b139ee45831f5e to your computer and use it in GitHub Desktop.
快排的非递归版本
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int partition(vector<int> &v, int low, int high) | |
{ | |
int pivot = v[low]; | |
while(low < high) | |
{ | |
while( (pivot <= v[high]) && low < high) | |
{ | |
high --; | |
} | |
v[low] = v[high]; | |
while( (pivot >= v[low] && low < high) | |
{ | |
low ++; | |
} | |
v[high] = v[low]; | |
} | |
v[low] = pivot; | |
return low; | |
} | |
void quick_sort(vector<int> &v, int low, int high) | |
{ | |
stack<int> s; | |
if(low<high) | |
{ | |
int pivot = partition(v, low, high); | |
if(low < pivot-1){ | |
s.push(low); | |
s.push(mid-1); | |
} | |
if(mid+1 < high){ | |
s.push(mid+1); | |
s.push(high); | |
} | |
int q, p; | |
while(!s.empty()){ | |
q = s.top(); | |
s.pop(); | |
p = s.top(); | |
s.pop(); | |
int mid = partition(v, p, q); | |
if(p< mid-1){ | |
s.push(p); | |
s.push(mid-1); | |
} | |
if(mid+1<q){ | |
s.push(mid+1); | |
s.push(q); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment