三种快速排序法

/*交换函数:为了提高效率,当所交换的两个元素值不相等时,用异或运算*/
void swap(int *a, int *b)
{
	if (*a != *b){
		*a = *a^*b;
		*b = *a^*b;
		*a = *a^*b;
	}
	else{
		int temp = *a;
		*a = *b;
		*b = temp;
	}
}

/*第一种快排:只有一个长度n,每次需计算出low和high指针*/
int QuickSort_process1(int *a, int n)
{
	int low, high, temp;
	low = 0;
	high = n - 1;
	temp = a[0];
	while (low < high){
		while (low < high&&temp <= a[high])
			--high;
		if (low < high)
			a[low] = a[high];
		while (low<high&&temp>a[low])
			++low;
		if (low < high)
			a[high] = a[low];
	}
	a[high] = temp;
	return high;
}
void QuickSort1(int *a,int n)
{
	int pos;
	if (n>0){
		pos = QuickSort_process1(a, n);
		QuickSort1(a, pos);
		QuickSort1(a + pos + 1, n - pos - 1);
	}
}

/*第二种快排:有两个指针,一个快,一个慢。快的指针找比基元素小的数,慢的指针指向比基元素小的最后一个元素*/
/*这样,在排序结束后,整个数组就被基元素分为了两部分。*/
int QuickSort_process2(int *a, int n)
{
	int first, second, temp;
	first = 0;
	second = -1;
	temp = a[n - 1];
	while (first != n){
		if (a[first] < temp){
			swap(a+second+1,a+first);
			++second;
		}
		++first;
	}
	swap(a + second + 1, a + n - 1);
	return second + 1;
}

void QuickSort2(int *a, int n)
{
	int pos;
	if (n > 0){
		pos = QuickSort_process2(a,n);
		QuickSort2(a, pos);
		QuickSort2(a + pos + 1, n - pos - 1);
	}
}

/*第三种快排,比较传统的那种,参数中有low指针和high指针*/
int QuickSort_process3(int *a, int low, int high)
{
	int l, h, temp;
	l = low;
	h = high;
	temp = a[low];
	while (l < h){
		while (l< h&&a[h] >= temp)
			--h;
		if (l < h)
			a[l] = a[h];
		while (l < h&&a[l] < temp)
			++l;
		if (l < h)
			a[h] = a[l];
	}
	a[h] = temp;
	return h;
}

void QuickSort3(int *a, int low,int high)
{
	int pos;
	if (low < high){
		pos = QuickSort_process3(a,low,high);
		QuickSort3(a,low,pos-1);
		QuickSort3(a,pos+1,high);
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值