快速排序

快速排序的核心思想:分治

1.先选取一个数作为基准数,一般选择分区的最左侧元素

2.分区过程,比基准数大的数放在右边,比基准数小的数放在左边。

3.对左右区间重复第二步,直到各区间只有一个数。

具体实现

low指向数组第一个元素(将其选为基准元素),high指向数组最后一个元素

第一步:high从右向左移动,若high指向的元素比l基准元素小(X_h<Xj),交换两个元素,low右移一位

第二步:low从左向右移动,若low指向的元素比基准元素大(X_l>X_j),交换两个元素,high左移一位

两步交替执行直到low=high时,跳出循环。比基准元素小的数都到了基准元素左侧,大的数都到了右侧。也就是代码中的Partition函数,返回的结果是基准元素的下标。

#include "iostream"
using namespace std;
int Partition(int a[8],int low, int high,int temp);//temp是基准元素的下标,令temp=low,选择分区最左侧元素作为基准元素
void QuickSort(int a[8], int low, int high);
int  main()
{
	int a[8] = { 61, 33, 48, 82, 72, 11, 25, 48 };
	int temp = 0;//存储基准元素所在位置
	QuickSort(a, 0, 7);
	for (int i = 0; i < 8; i++)
		cout << a[i]<<" ";
	system("pause");
	return 0;
}
//大的数在基准元素右侧,小的数在基准元素左侧,从小到大排列
int Partition(int a[8],int low, int high,int temp)
{
	while (low < high)
	{
		while (low<high)
		{
			if (a[temp] > a[high])//交换位置
			{
				int demo;
				demo = a[temp];
				a[temp] = a[high];
				a[high] = demo;
				temp = high;//temp是基准元素下标
				break;
			}
			high--;//high从右向左搜寻
		}
		
		low = low + 1;
		while (low < high)
		{
			if (a[low] > a[temp])
			{
				int demo;
				demo = a[temp];
				a[temp] = a[low];
				a[low] = demo;
				temp = low;
				break;
			}
			low++;
		}
		
		high = high - 1;
	}
	for (int i = 0; i < 8; i++)
		cout << a[i] << " ";
	cout << endl;
	return temp;
	
}
void QuickSort(int a[8], int low, int high)
{
	if (low < high)
	{
		int temp = Partition(a, low, high, low);//默认将每个划分的最左侧元素当作基准元素
		QuickSort(a, low, temp - 1);
		QuickSort(a, temp + 1, high);
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值