递归实现
#include <iostream>
using namespace std;
int getDiv(int a[],int low, int high){
int i=low;
int j=high;
int key=a[low];
while (i<j) {
while (i<j&&a[j]>key) {//注意边界条件
--j;
}
if (i<j) {
a[i++]=a[j];
}
while (i<j&&a[i]<key) {
++i;
}
if (i<j) {
a[j--]=a[i];
}
}
a[i]=key;
return i;
}
void QuickSort(int a[],int low,int high){
if (low<high) {
int target=getDiv(a,low,high);
QuickSort(a, low, target-1);
QuickSort(a, target+1,high);
}
}
int main(){
int a[10]={9,8,7,6,5,4,3,2,1,0};
QuickSort(a, 0, 9);
for (int i=0; i<10; i++) {
cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}
解法2:
#include <iostream>
using namespace std;
void swap(int *a,int *b){
int tmp=*a;
*a=*b;
*b=tmp;
}
int getMid(int arr[],int begin,int end){
int key=arr[end];
int j=begin-1;
for (int i=begin; i<end; i++) {
if (arr[i]<=key) {
j++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[j+1], &arr[end]);
return j+1;
}
void quickQort(int arr[],int begin,int end){
if (begin<end) {
int mid=getMid(arr,begin,end);
quickQort(arr, begin, mid-1);
quickQort(arr, mid+1, end);
}
}
int main(){
int a[10]={10,9,8,7,6,5,4,3,2,1};
quickQort(a, 0, 9);
for (int i=0; i<10; i++) {
cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}
非递归实现
#include <iostream>
#include <stack>
using namespace std;
int getDiv(int a[],int low, int high){
int i=low;
int j=high;
int key=a[low];
while (i<j) {
while (i<j&&a[j]>key) {//注意边界条件
--j;
}
if (i<j) {
a[i++]=a[j];
}
while (i<j&&a[i]<key) {
++i;
}
if (i<j) {
a[j--]=a[i];
}
}
a[i]=key;
return i;
}
void QuickSort(int a[],int low,int high){
if (low<high) {
stack<int> stk;//stk中存储要排序元素的上下边界
stk.push(low);
stk.push(high);
while (!stk.empty()) {
int r=stk.top();
stk.pop();
int l=stk.top();
stk.pop();
if (l<r) {
int mid=getDiv(a, l, r);
stk.push(l);
stk.push(mid-1);
stk.push(mid+1);
stk.push(r);
}
}
}
}
int main(){
int a[10]={9,3,7,4,5,6,8,2,1,0};
QuickSort(a, 0, 9);
for (int i=0; i<10; i++) {
cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}
参考: 快排非递归