算法通关村第十关青铜挑战——什么是快速排序

大家好,我是怒码少年小码。

快速排序

  1. 选取pivot中心轴
  2. 将大于pivot中心轴的元素放在中心轴的右边
  3. 将小于pivot中心轴的元素放在中心轴的左边
  4. 重复上述过程

实现方式一:

cpp 复制代码
void  quickSort(int arr[], int left, int right) {
	if (left < right) {
		int pivot = arr[right];
		int i = left - 1;
		for (int j = left; j < right; j++) {
			if (arr[j] < pivot) {
				i++;
				int temp = arr[i];
				arr[i] = arr[j];
				arr[j] = temp;
			}
		}
		//哨兵移动到位置pivotIndex上
		int pivotIndex = i + 1 ;
		int temp = arr[pivotIndex];
		arr[pivotIndex] = arr[right];
		arr[right] = temp;

		quickSort(arr, left, pivotIndex - 1);
		quickSort(arr, pivotIndex + 1, right);
	}
	//输出查看
	for (int i = 0; i < right + 1; i++) {
		cout << arr[i] << ",";
	}
	cout << endl;
}

看到这么多的代码是不是怕了呀,不怕,我们一起看。

这段代码中我们把pivot保存数组中最右边的元素为基准。定义一个变量i保存需要交换元素的前一个元素。定义一个变量j从左至右遍历数组判断是否需要交换。最后再用递归实现一直重复的过程。

实现方式二:

下面这种方式就更好理解了取中间结点为pivot,left和right用于遍历和比较,当满足left <= right 并且要找到不符合条件的元素后就停下来,执行交换。可以输出打印检查看看对不对。最后再递归地重复这个过程。

cpp 复制代码
void quickSort01(int arr[], int start, int end) {
	if (start >= end) {
		return;
	}
	int left = start, right = end;
	int pivot = arr[(start + end) / 2];

	while (left <= right) {
		while (left <= right && arr[left] < pivot) {
			left++;
		}
		while (left <= right && arr[right] > pivot) {
			right--;
		}
		if (left <= right) {
			int temp = arr[left];
			arr[left] = arr[right];
			arr[right] = temp;
			left++;
			right--;
		}
	}
	for (int i = 0; i < right + 1; i++) {
		cout << arr[i] << ",";
	}
	cout << endl;
	quickSort(arr, start, right);
	quickSort(arr, left, end);
}
相关推荐
203号居民26 分钟前
LeetCode hot 100 — 141. 环形链表2
算法·leetcode·链表
玖玥拾1 小时前
LeetCode 202 快乐数
算法·leetcode
LuminousCPP1 小时前
数据结构-二叉树(六):BFS层序遍历与完全二叉树判断|复用链式队列 + (N_0=N_2+1) 性质证明
c语言·数据结构·笔记·算法·二叉树·宽度优先
ZhouDevin2 小时前
算法论文/数据集3——CLD(TMLR2025)压缩训练集,仅保留对验证集有益的样本
人工智能·深度学习·算法·计算机视觉
码匠许师傅2 小时前
【设计模式精讲】14.外观模式(Facade)
c++·设计模式·uml·外观模式
Tim_102 小时前
【LeetCode】29、两数相除
算法·leetcode·职场和发展
纪念 2292 小时前
数据结构排序(三)
数据结构
船厂电气自动化ai大模型3 小时前
AI大模型与数学/第63课:矩阵定义、矩阵加法、标量乘法(逐级精讲)
数据结构·人工智能·深度学习·线性代数·算法
余额瞒着我当琳3 小时前
算法修炼 chapter 2 双指针进阶、盛最多水的容器、有效三角形的个数、两数之和、三数之和、四数之和
算法
你压到我腿毛了6663 小时前
C语言冒泡算法(Bubble sort)
c语言·数据结构·算法