快速排序
// quick_sort.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
void quick_sort(int *A,int left,int right){//方法一
int i = left;
int j = right;
int flag = left;
int key = A[left];
while(i != j){
while(i < j&&A[j] >= key)j--;
if(A[j] < key){
A[flag] = A[j];
flag = j;
}
while(i < j&&A[i] <= key)i++;
if(A[i] > key){
A[flag] = A[i];
flag = i;
}
}
A[flag] = key;
for(int k = 0;k < 9;k++)cout<<A[k]<<endl;
cout<<endl;
if(left < i){
quick_sort(A,left,i);
}
if(i+1 < right){
quick_sort(A,i+1,right);
}
}
void quick_sort(int *a,int p,int q){//方法二
if(p<q){
int temp = 0;
int x = a[p];
int i = p;
for(int j = p+1;j <= q;++j){
if(a[j] < x){
++i;
temp = a[i];/*exchange a[i] with a[p]*/
a[i] = a[j];
a[j] = temp;
}
}
temp = a[p];/*exchange a[i] with a[p]*/
a[p] = a[i];
a[i] = temp;
quick_sort(a,p,i-1);
quick_sort(a,i+1,q);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[] = {55,4,66,2,1,33,65,5};/*test data*/
quick_sort(a,0,7);
for(int i = 0;i<8;++i){cout<<a[i]<<" "<<endl;}
while(1);
return 0;
}