快速排序模板(略)


//测试案例:49 38 65 97 76 13 27 49
#include<iostream>
#include<ctime> 
#include<stdlib.h>
using namespace std;
//==================================================================================================================
//2.3快速排序
/*
1.选择待排序的表中第一个记录作为枢纽,枢纽记录暂时记录在r[0]上,设2个指针low和high,分别指向下界,上界,low=1,high=length
2.从最右向左依次搜索,找到第一个关键字比枢纽关键字privotkey小的记录,将其移到low处,具体:
当low<high时,若high处的值比privotkey的值大或等,左移high指针,否则high记录给予privotkey
3.从最左向右依次搜索,找到第一个关键字比枢纽关键字privotkey大的记录,将其移到high处,具体:
当low<high时,若low处的值比privotkey的值小或等,右移high指针,否则low记录给予high
4.重复上述2,3步骤,直到low==high,原表分成2个子表
*/
//特点:取决于递归树的深度,时间复杂度o(nlog2n),不稳定,适合顺序结构,适合无序,n大的情况
//2.3.1找到枢纽,从大到小
int Partition(int A[], int low, int high, int length) {
	int privotkey = A[low];
	while (low < high) {

		while (low < high && A[high] >= privotkey)
			high--;
		A[low] = A[high];

		while (low < high && A[low] <= privotkey)
			low++;
		A[high] = A[low];
	}
	A[low]=privotkey ;
	return low;
}
//2.3.2排序
void Qsort(int A[], int low, int high, int& length) {
	if (low < high) {
		int pivotloc = Partition(A, low, high, length);
		Qsort(A, low, pivotloc - 1, length);
		Qsort(A, pivotloc + 1, high, length);
	}
}
//算法分析
/*
时间复杂度
(1)趟数取决于递归树的深度
(2)最好情况,类似折半查找
(3)最坏情况:已经排好序
平均:O(n*log2n)
空间复杂度
递归,需要栈
最坏o(n),最好o(log2n)
特点:
(1)记录非顺次的移动导致不稳定
(2)排序过程中需要定义上下界,适合顺序结构
(3)当N很大,无序时,最适合
*/
int main() {
	int* a = new int[9];
	int length = 8;
	srand(unsigned(time(NULL)));
	for (int i = 1; i <= 8; i++) {
		// a[i]=rand()% 90 + 10;
		cin >> a[i];
	}
	cout << "==============" << endl;
	cout << "快速排序:" << endl;
	cout << "==============" << endl;
	cout << "before sort:" << ends;
	for (int i = 1; i <= length; i++) {
		cout << a[i] << " ";
	}
	cout << endl;
	Qsort(a, 1, length, length);
	cout << "after sort:" << ends;
	for (int i = 1; i <= length; i++) {
		cout << a[i] << " ";
	}
	cout << endl;
	delete a;
	a = NULL;
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

广大菜鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值