网络版本
#include<iostream>
using namespace std;
int partition(int left, int right ,int data[]) {
int pivot = data[left];//pivot等于最左边的数
while (left < right) {
while (left < right && data[right] >= pivot)//最右边开始,直到找到比pivot小的数
right--;
if (left < right)
{ data[left] = data[right];//把最左边换成那个值
left++; //左边加1
}
while (left < right && data[left] <= pivot)//遍历左边,直到找到左边的比pivot大
left++;
if (left < right)
{data[right] = data[left];//右边等于左边
right--;//右边减1
}
}
data[left] = pivot;//左边==pivot
return left;
}
void quicksort(int left, int right,int data[]) {
int dp;
if (left < right) {
dp = partition(left, right,data);
quicksort(left, dp - 1,data);
quicksort(dp + 1, right,data);
}
}
void main(){
int a[6]={33,51,49,11,24,3};
quicksort(0,5,a);//0->n-1
for(int i=0;i<6;i++)
cout<<a[i]<<" ";
system("pause");
}
精简版本
void swap(int &x, int &y){
int tmp = x;
x = y;
y = tmp;
}
int partition(int l, int r, int data[]){
int x = l;
int key = data[l];
for(int y = l + 1; y <=r; y++){
if(data[y] < key) {
x++;
swap(data[x], data[y]);
}
}
swap(data[l], data[x]);
return x;
}
void QSort(int l, int r, int data[]){
if(l >= r) return;
int pos = partition(l, r, data);
QSort(l, pos - 1, data);
QSort(pos + 1, r, data);
}
Java版本
private void qs(int low,int high) {
int l = low;
int h = high;
int povit = data[low];
while (l<h) {
while (l<h&&povit<=data[h]) h--;
if (l<h) {
int tmp = data[h];
data[h] = data[l];
data[l] = tmp;
l++;
}
while (l<h&&povit>=data[l]) l++;
if (l<h) {
int tmp = data[h];
data[h] = data[l];
data[l] = tmp;
h--;
}
}
if (l>low) qs(low, l-1);
if (h<high) qs(l+1, high);
}