选左侧第一个数为基准数,从右侧开始找一个比基准数小的数,从左侧开始找一个比其大的数,二者调换,再接着找,直到两向相遇,则将相遇点的数据与基准数调换;接着对基准数两侧的数据进行与上述相同的操作,进行递归处理。
#include <iostream>
using namespace std;
//快速排序,在子函数中,数组已被改变
void quick_sort(int *a, int left, int right) //left和right为索引值
{
int temp; //存储每次选定的基准数(从最左侧选基准数)
int t;
int initial=left;
int end=right;
temp=a[left];
//***必须有这一部分***//
if (left>right) //因为在递归过程中有减1加1的情况,当其越界时,直接return,不返回任何值,即结束当前程序块
return;
while(left!=right) //此时左右index在移动中,若left==right,则跳出循环,将基数归位
{
while(a[right]>=temp && left<right) //直到找到小于基准数的值为准
right--;
while(a[left]<=temp && left<right)
left++;
if(left<right) //交换左右两侧值,当left=right时,跳出外层while循环
{
t=a[right];
a[right]=a[left];
a[left]=t;
}
}
a[initial]=a[left];
a[left]=temp; //基数归位
//递归处理归位后的基准数的左右两侧
quick_sort(a,initial,left-1); //此时left=right
quick_sort(a,left+1,end);
}
int main()
{
int a[20];
int n;
cout<<"请输入需排序的数组的个数:\n";
cin>>n;
cout<<"请输入数组元素:\n";
for (int i=0;i<n;i++)
cin>>a[i];
quick_sort(a,0,n-1);
cout<<"排序结果:\n";
for (int j=0;j<n;j++)
cout<<a[j]<<" ";
cout<<endl;
system("pause");
return 0;
}