排序算法-快速排序法(QuickSort)

排序算法-快速排序法(QuickSort)

1、说明

快速排序法是由C.A.R.Hoare提出来的。快速排序法又称分割交换排序法,是目前公认的最佳排序法,也是使用分而治之(Divide and Conquer)的方式,会先在数据中找到一个虚拟的中间值,并按此中间值将所有打算排序的数据分为两部分。其中小于中间值的数据放在左边,而大于中间值的数据放在右边,再以同样的方式分别处理左右两边的数据,直到排序完为止。操作与分割步骤如下:

假设有n项记录,其键值为

  1. 先假设K的值为第一个键值。
  2. 从左向右找出键值,使得
  3. 从左向右找出键值,使得
  4. 如果,那么互换,并回到步骤2。
  5. 如果,那么将互相,并以为基准点分割成左、右两部分,然后针对左、右两边执行步骤1~5,直到左边键值等于右边键值为止。

2、算法分析

  1. 在最好情况和平均情况下,时间复杂度为。在最坏情况下就是每次挑中的中间值不是最大就是最小的,其时间复杂度为
  2. 快速排序法不是稳定排序法。
  3. 在最坏情况下,空间复杂度为,而在最好情况下,空间复杂度为
  4. 快速排序法是平均运行时间最快的排序法。

3、C++代码

cpp 复制代码
#include<iostream>
using namespace std;

void Print(int tempData[], int tempSize) {
	for (int i = 0; i < tempSize; i++) {
		cout << tempData[i] << "  ";
	}
	cout << endl;
}

void Quick(int tempData[], int tempLeft, int tempRight) {
	int temp;
	int leftIndex;
	int rightIndex;
	int t;
	if (tempLeft < tempRight) {
		leftIndex = tempLeft + 1;
		rightIndex = tempRight;
		while (true) {
			for (int i = tempLeft + 1; i < tempRight; i++) {
				if (tempData[i] >= tempData[tempLeft]) {
					leftIndex = i;
					break;
				}
				leftIndex++;
			}
			for (int j = tempRight; j > tempLeft + 1; j--) {
				if (tempData[j] <= tempData[tempLeft]) {
					rightIndex = j;
					break;
				}
				rightIndex--;
			}
			if (leftIndex < rightIndex) {
				temp = tempData[leftIndex];
				tempData[leftIndex] = tempData[rightIndex];
				tempData[rightIndex] = temp;
			}
			else {
				break;
			}
		}
		if (leftIndex >= rightIndex) {
			temp = tempData[tempLeft];
			tempData[tempLeft] = tempData[rightIndex];
			tempData[rightIndex] = temp;

			Quick(tempData, tempLeft, rightIndex - 1);
			Quick(tempData, rightIndex + 1, tempRight);
		}
	}
}

int main() {
	const int size = 10;
	int data[100] = { 32,5,24,55,40,81,17,48,25,71 };
	//32  5  24  55  40  81  17  48  25  71
	//32  5  24  25  40  81  17  48  55  71
	//32  5  24  25  17  81  40  48  55  71
	//17  5  24  25  32  81  40  48  55  71
	//5  17  24  25  32  81  40  48  55  71
	//5  17  25  24  32  81  40  48  55  71
	//5  17  25  24  32  71  40  48  55  81
	//5  17  25  24  32  55  40  48  71  81
	//5  17  25  24  32  48  40  55  71  81
	//5  17  25  24  32  40  48  55  71  81
	Print(data, size);
	Quick(data, 0, size - 1);
	Print(data, size);
	return 0;
}

输出结果

相关推荐
励志不掉头发的内向程序员10 分钟前
STL库——string(类模拟实现)
开发语言·c++
王廷胡_白嫖帝12 分钟前
Qt文件压缩工具项目开发教程
java·开发语言·qt
张飞洪32 分钟前
C# 13 与 .NET 9 跨平台开发实战:基于.NET 9 与 EF Core 9 的现代网站与服务开发
开发语言·c#·.net
郝学胜-神的一滴38 分钟前
使用C++11改进工厂方法模式:支持运行时配置的增强实现
开发语言·c++·程序人生·设计模式
我是场1 小时前
Android14内核调试 - boot & vendor_boot
java·开发语言·spring boot
爱和冰阔落1 小时前
从关机小游戏学 C 语言:分支循环 + 关键字(break/continue)实战
c语言·开发语言
Korloa1 小时前
表达式(CSP-J 2021-Expr)题目详解
c语言·开发语言·数据结构·c++·算法·蓝桥杯·个人开发
手握风云-1 小时前
回溯剪枝的 “减法艺术”:化解超时危机的 “救命稻草”(一)
算法·机器学习·剪枝
yodala2 小时前
C++中的内存管理(二)
开发语言·c++
屁股割了还要学2 小时前
【数据结构入门】排序算法:插入排序
c语言·开发语言·数据结构·算法·青少年编程·排序算法