一、快速排序算法详解

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

二、快速排序代码实现(C++)

#include<iostream>
#include<vector>

using namespace std;

//分割函数
int Partition(vector<int>& A, int low, int high)
{
	int pivot = A[low];
	while (low < high)
	{
		while (low < high && A[high] >= pivot)
		{
			high--;
		}
		A[low] = A[high];
		while (low < high && A[low] <= pivot)
		{
			low++;
		}
		A[high] = A[low];
	}
	A[low] = pivot;
	return low;
}

//快排函数
void QuickSort(vector<int>& A, int low, int high)
{
	if (low < high)
	{
		int pivot = Partition(A, low, high);
		QuickSort(A, low, pivot - 1);
		QuickSort(A, pivot + 1, high);
	}
}

//快速排序2
int Partition1(vector<int>& A, int low, int high)
{
	int pivot = A[low];
	while (low < high)
	{
		while (low < high && A[low] >= A[high])high--;
		while (low < high && A[low] <= A[high])low++;
		swap(A[low], A[high]);
	}
	swap(A[low], pivot);
	return low;
}
void QuickSort1(vector<int>& A, int low, int high)
{
	if (low < high)
	{
		int pivot = Partition(A, low, high);
		QuickSort1(A, low, pivot - 1);
		QuickSort1(A, pivot + 1, high);
	}
}

int main()
{
	// 构造一个数组
	vector<int> arr;
	arr.push_back(2);
	arr.push_back(4);
	arr.push_back(1);
	arr.push_back(0);
	arr.push_back(3);
	arr.push_back(5);
	int N = arr.size();
	cout << "输出数组的长度为:" << N << endl;

	//排序前输出
	cout << "排序前的结果输出:";
	for (vector<int>::iterator it = arr.begin(); it != arr.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
	cout << "排序后的结果输出:";
	QuickSort1(arr, 0, N - 1);
	cout << "快速排序后:";
	for (vector<int>::iterator it = arr.begin(); it != arr.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;

	system("pause");
	return 0;
}

三、学习链接

力扣-快速排序
菜鸟教程-快速排序

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐