快速排序--小结

#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);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值