快速排序 Quick Sort
:快速排序排序效率在同为O(N*logN)的几种排序方法中效率较高,实际上是一种交换排序。:采用分治法
该方法的基本思想是:
1、从数列中挑出一个元素,称为 "基准"(pivot);
2、重新排序数列,所有元素比基准值小的摆放在基准前面,大的摆在基准的后面:分区(partition)操作。
3、递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序。
--快排有很多种版本。例如,我们“基准数”的选择方法不同就有不同的版本
<pre name="code" class="cpp">#include<iostream>
#include<string>
using namespace std;
int circle=0;
//参考大话数据结构----方法一
void QuickSort(int *pdata,int low,int high)
{
if (low<high)
{
int first=low,last=high;
int key=pdata[first];
while (first<last)
{
while (first<last&&pdata[last]>=key) //从右向左找第一个小于标准值的位置
last--;
if(first<last)
pdata[first]=pdata[last]; //小的数排到前面
while (first<last&&pdata[first]<=key) //从左向右找比key小的值的位置,位置正确就不会进行调整
first++;
if(first<last)
pdata[last]=pdata[first]; //大的数排到后面
cout<<"the "<<++circle<<"round:";
}
pdata[first]=key;
for(int i=0;i<10;i++)
cout<<pdata[i];
cout<<endl;
QuickSort(pdata,low,first-1); //以first为中心分成两部分,
QuickSort(pdata,first+1,high);
}
}
//方法二
//参考 http://developer.51cto.com/art/201403/430986.htm#commment
//很好理解(巡视的数组元素,不是比基准大的,就是比基准小的)
void quickSort(int *pdata,int left,int right)
{
if (left>=right)
{
return;
}
if(left<right)//如果需要排序的元素大于1个
{
int temp=0;
int key=pdata[left];
int i=left,j=right;
while (i!=j)
{
while (pdata[j]>=key&&i<j) //右边的哨兵开始向左巡逻
j--;
while(pdata[i]<=key&&i<j) //左边的哨兵开始训练
i++;
if (i<j) //如果两个哨兵没有相遇,则数据进行交换
{
temp=pdata[j];
pdata[j]=pdata[i];
pdata[i]=temp;
}
cout<<"the "<<++circle<<"round:";
}
pdata[left]=pdata[i];//i停的位置即<key的位置,i的值放到最左边
pdata[i]=key;//基准位归位
for(int m=0;m<10;m++)
cout<<pdata[m];
cout<<endl;
quickSort(pdata,left,i-1);//以i的位置为基准,分成两部分,左部分
quickSort(pdata,i+1,right);//右半部分
}
}
int main()
{
int data[]={6,1,2,7,9,3,4,5,10,8};
int data2[]={1,2,3,4,5,6};
int data3[]={9,8,7,6,5,4,3,2,1};
int data4[]={1,2,3,4,5,6,7,8,9};
cout<<"----------------------------------"<<endl;
quickSort(data,0,9);
for(int i=0;i<10;i++)
cout<<data[i]<<' ';
cout<<endl;
return 0;
}
确实有些难度,对我来说,得好好理解一下递归结构!