快速排序

//快速排序思想
//选取一个基准值一般选取右值,从前往后遍历找到一个小于基准值的值然后停下来,从后往前找一个大于基准值的值然后停下来
//交换left,right此时,继续向后,向前遍历,直到找到left=right的时候,那么就第一次遍历完成,然后交换基准值与left=right的值
//此时的结果是划分为了两个区间,继续按照上述方法排序,直到每一个小区间只剩下一个值的时候就排序完成。

//时间复杂度O(NLogN) 最坏时间复杂度(O(N^2))
//优化方案 选区基准值为(比较左右中下标的大小,选区中间值)
//—因为如果选区基准值接近数组数据的最大值或者最小值,快速排序最坏情况就发生了


//==================递归实现==快速排序


//交换函数
int PartSort(int arr[], int left, int right)
{
	if (right - left <= 1)
		return left;
	int left_index = left;
	int right_index = right;
	int basic_value = arr[right - 1];
	while (left_index < right_index)
	{
		while (left_index < right_index&&arr[left_index] < basic_value) 
			left_index++;
		while (left_index<right_index&&arr[right_index]>=basic_value)
			right_index--;
		Swap(&arr[left_index], &arr[right_index]);
	}
	Swap(&arr[left_index], &arr[right - 1]);
}
//递归函数
void _QuickSort(int arr[], int left, int right)
{
	if (arr == NULL || right - left <= 1)
		return;
	int mid = PartSort(arr, left, right);
	_QuickSort(arr, left, mid);
	_QuickSort(arr, mid + 1, right);
}
//主函数
void QuickSort(int arr[], int size)
{
	if (arr == NULL || size <= 1)
		return;
	int left = 0;
	int right = size;
	_QuickSort(arr, left, right);
}

//=================非递归实现===快速排序


//交换函数
int PartSort(int arr[], int left, int right)
{
	if (right - left <= 1)
		return left;
	int left_index = left;
	int right_index = right - 1;
	int basic_value = arr[right - 1];

	while (left_index < right_index)
	{
		while (left_index < right_index&&arr[left_index] < basic_value)
			left_index++;
		while (left_index < right_index&&arr[right_index] >= basic_value)
			right_index--;
		Swap(&arr[left_index], &arr[right_index]);
	}
	Swap(&arr[left_index], &arr[right - 1]);
}

//非递归函数
void _QuickSort(int arr[], int left, int right)
{
	stack<int>s;
	s.push(right);
	s.push(left);
	while (!s.empty())
	{
		int begin = s.top(); //划分左区间
		s.pop();
		int end = s.top();  //划分右区间
		s.pop();
		int mid = PartSort(arr, begin, end);
		if (begin < mid - 1)  //模拟递归左区间
		{
			s.push(mid - 1);
			s.push(begin);
		}
		if (mid + 1 < end)   //模拟递归右区间
		{
			s.push(end);
			s.push(mid + 1);
		}
	}
}
void QuickSort(int arr[], int size)
{
	if (arr == NULL || size <= 1)
		return;
	int left = 0;
	int right = size;
	_QuickSort(arr, left, right);
	return;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值