数据结构:快速排序及其优化

快速排序:

快速排序的基本思想是:通过一趟排序将待排序记录分割成独立的两部分,其中一部分记录的关键字均比另一部分记录的关键字小,则可对这两部分继续进行排序,以达到整个序列有序的目的。
下面为快速排序。
还有优化方案:
Partition函数实现取一个基准点
1.随机取基准点
2.三数取中优化
3.小数据量(使用插入排序)
4.聚集优化
2,3,4合起来为快速排序的最高优化

void Swap(int arr[], int firstindex, int secondindex)
{
	int temp = arr[firstindex];
	arr[firstindex] = arr[secondindex];
	arr[secondindex] = temp;
}
//函数处理完成后  中间大的数在left位置
void MvMiddleMaxNum(int arr[], int left, int mid, int right)
{
	if (arr[mid] > arr[right])//mid位置是后面较大的  right是较小的
	{
		Swap(arr, mid, right);
	}
	if (arr[left] < arr[right])
	{
		Swap(arr, left, right);
	}
	if (arr[left] > arr[mid])
	{
		Swap(arr, left, mid);
	}
}
int Partition(int arr[], int left, int right)
{
	int boundkey = arr[left];
	while (left < right)
	{
		while (left < right && arr[right] >= boundkey)right--;
		arr[left] = arr[right];
		while (left < right && arr[left] <= boundkey)left++;
		arr[right] = arr[left];
	}
	arr[left] = boundkey;
	return left;
}
void MyInsertSort(int arr[], int left, int right)
{
	int temp = 0;
	int i = left + 1;
	int j = i - 1;
	for (i = left + 1; i <= right; i++)
	{
		temp = arr[i];
		for (j = i - 1; j >= left && arr[j] > temp; j--)
		{
			arr[j + 1] = arr[j];
		}
		arr[j + 1] = temp;
	}
}
void Quick(int arr[], int startindex, int endindex)
{
	if (startindex < endindex)
	{
		if (endindex - startindex < 20)
		{
			MyInsertSort(arr, startindex, endindex);
		}
		int midindex = (startindex + endindex) / 2;
		MvMiddleMaxNum(arr, startindex, midindex, endindex);
		//Swap(arr, startindex, (rand() % (endindex - startindex + 1) + startindex));
		int k = Partition(arr, startindex, endindex);
		//聚集优化  一趟快排之后 
		Quick(arr, startindex, k - 1);
		Quick(arr, k + 1, endindex);
	}
}
void Quick1(int arr[], int startindex, int endindex)
{
	int l = startindex;
	int r = endindex;
	int* st = (int*)malloc(sizeof(int)*(endindex - startindex + 1) * 2);
	int top = 0;
	st[top++] = endindex;
	st[top++] = startindex;
	while (top != 0)
	{
		l = st[top - 1]; top--;
		r = st[top - 1]; top--;
		int k = Partition(arr, l, r);
		if (k + 1 < r)//右边区间有两个元素
		{
			st[top++] = r;
			st[top++] = k + 1;
		}
		if (l < k - 1)//左边区间有两个元素
		{
			st[top++] = k - 1;
			st[top++] = l;
		}
	}
	free(st);
}
void QuickSort(int arr[], int len)
{
	Quick1(arr, 0, len - 1);
}

由于时间有点紧:改天详细描述。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值