三种快速排序法

/*交换函数:为了提高效率,当所交换的两个元素值不相等时,用异或运算*/
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
    评论
快速排序法是一种基础的排序算法,其基本思想是通过一趟排序将待排序序列分为两部分,其中一部分的所有元素都比另一部分的所有元素小,然后再对这两部分分别进行排序,最终将整个序列排好序。 下面是用C语言实现快速排序的示例代码: ```c void quick_sort(int arr[], int left, int right) { int i, j, pivot, temp; if (left < right) { i = left; j = right; pivot = arr[left]; while (i < j) { while (i < j && arr[j] >= pivot) j--; if (i < j) arr[i++] = arr[j]; while (i < j && arr[i] < pivot) i++; if (i < j) arr[j--] = arr[i]; } arr[i] = pivot; quick_sort(arr, left, i - 1); quick_sort(arr, i + 1, right); } } ``` 在这段代码中,我们使用了递归来实现快速排序。首先定义一个 `quick_sort` 函数,其中 `left` 和 `right` 分别表示待排序序列的左右边界。如果左边界小于右边界,就进行下一步操作。接着定义三个变量 `i`、`j` 和 `pivot`,其中 `i` 和 `j` 分别指向序列的左右两端,`pivot` 则用于记录当前的枢轴元素,初始时我们选择序列的第一个元素作为枢轴元素。然后在一个 `while` 循环中,依次将 `i` 和 `j` 向中间移动,直到找到需要交换的元素对。如果 `i` 小于 `j`,就将这两个元素进行交换。这样一轮循环下来,枢轴元素就被放置在了正确的位置上。然后再递归地对左右两部分进行排序,这样一直递归下去,直到整个序列排好序为止。 快速排序的时间复杂度为 $O(n\log n)$,是一种高效的排序算法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值