快速排序方法有很多,最近总结了一些。今天总结的是姑且记为快速排序(1),其方法的原理很简单,对于一组数列将最左边的数设定为轴,并记录其值为s,然后进行廻圈处理:
1.从S值开始以索引i往数组右边搜索,直到找到大于s 的数
2.从数组最后一个数开始以索引j向左搜索,直到找到小于s 的数
3.如果两个索引i>j,则结束循环
4.如果i < j,则交换索引i与j两处的值
5.将左侧的轴与j 进行交换
6.对轴左边进行递回对轴右边进行递回
#include <iostream>
#include <stdlib.h>
using namespace std;
#define swap(x,y){int t=x;x=y;y=t;}
void fast_shot(int number[],int begin,int end);
int main()
{
int number[10]={11, 25, 11, 4, 88, 2, 108, 3, 2, 21};
fast_shot(number,0,9);
for(int i = 0; i < 9; i++)
{
cout << number[i] << " ";
}
cout<<endl;
system("pause");
}
void fast_shot(int number[],int begin,int end)
{ int s,i,j;
if(begin<end)//递归的判定条件
{
s=number[begin];
i= begin - 1;
j= end + 1;
while(1)
{
while (i+1<j&&number[++i]<s);//当搜索完毕或者找到一个比S大的数时候跳出循环
while(j-1>-1&&number[--j]>s);
if(i>=j)
break; //如果I>J则证明全部搜索完毕
swap(number[i],number[j]);
}
number[begin]=number[j];
number[j]=s;
fast_shot(number,begin,j-1);//左边序列递归
fast_shot(number,j+1,end);//右边递归
}
}