#include <stdio.h>
int Partion(int a[],int low,int high)
{
int pivot,i,j;
if(low<high)
{
i=low,j=high;
pivot=a[low];
while(i<j)
{
while(j>i && a[j]>=pivot)
j--;
a[i]=a[j];
while(i<j && a[i]<=pivot)
i++;
a[j]=a[i];
}
a[i]=pivot;
}
return i;
}
//另一种partion方法:即设置两个指示符,一个表示比pivot小的数值边界,另一个不断向后循环,一旦找到一个比
//pivot小的数值,就讲它与前面的指示符所指向的数字对调
/*******
pivot=12
^ ^ *
23 33 45 12 6 8 2 44
^ ^ *
(1): 23 33 45 44 6 8 2 12
^ ^ *
(2): 6 33 45 44 23 8 2 12
^ ^ *
(3): 6 8 45 44 23 33 2 12
^ *
(4): 6 8 45 2 23 33 44 12
*******/
int Partion(int a[],int low,int high)
{
int pivot,p1,p2,k,tmp;
k=RandIndex(low,high);//随机产生一个数字,作为pivot;
pivot=a[k];
//将该pivot与a[high]对调
tmp=a[high];
a[high]=a[k];
a[k]=tmp;
//设置小于pivot的指示符(即p1始终指向小于pivot的数值边界,p2用于循环遍历数组)
p1=low-1;
for(p2=low;p2<high;p2++)
{
if(a[p2]<pivot)
{
p1++;
if(p1!=p2)
{
tmp=a[p2];
a[p2]=a[p1];
a[p1]=tmp;
}
}
}
p1++;
//将末尾的pivot值再次对调到中间适当的位置上。
tmp=a[high];
a[high]=a[p1];
a[p1]=tmp;
return p1;
}
void quick_sort(int a[],int low,int high)
{
int pivot;
if(low<high)
{
pivot=Partion(a,low,high);
quick_sort(a,low,pivot-1);
quick_sort(a,pivot+1,high);
}
}
快速排序--小结
最新推荐文章于 2023-02-28 18:43:36 发布