C++快速排序算法实现与讲解
C++快速排序算法实现与讲解
快速排序是一种高效的排序算法,采用分治法策略。以下是用 C++ 实现快速排序的示例代码:
#include <iostream>
#include <vector>
using namespace std;
int partition(vector<int>& arr, int low, int high) {
int pivot = arr[high]; // 选择最后一个元素作为基准值
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return i + 1;
}
void quickSort(vector<int>& arr, int low, int high) {
if (low < high) {
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
void printArray(const vector<int>& arr) {
for (int num : arr) {
cout << num << ' ';
}
cout << endl;
}
int main() {
vector<int> arr = {5, 2, 9, 1, 3, 6, 8, 7, 4};
int n = arr.size();
cout << 'Original array: ';
printArray(arr);
quickSort(arr, 0, n - 1);
cout << 'Sorted array: ';
printArray(arr);
return 0;
}
代码解析
这段代码实现了快速排序算法,并通过一个示例演示了如何使用该算法对整数数组进行排序。
-
partition函数:- 选择数组最后一个元素作为基准值
pivot。 - 遍历数组,将小于等于
pivot的元素放到左侧,大于pivot的元素放到右侧。 - 返回
pivot的最终位置。
- 选择数组最后一个元素作为基准值
-
quickSort函数:- 递归函数,接收数组、起始索引和结束索引作为参数。
- 如果起始索引小于结束索引,调用
partition函数将数组划分成两部分。 - 递归地对左右两部分进行排序。
-
printArray函数:- 辅助函数,用于打印数组元素。
-
main函数:- 创建一个示例数组
arr。 - 调用
printArray函数打印原始数组。 - 调用
quickSort函数对数组进行排序。 - 再次调用
printArray函数打印排序后的数组。
- 创建一个示例数组
总结
快速排序是一种高效的排序算法,平均时间复杂度为 O(n log n)。本篇博客提供了使用 C++ 实现快速排序的详细代码和解释,希望能够帮助您理解和掌握这一重要的排序算法。
原文地址: http://www.cveoy.top/t/topic/Nz8 著作权归作者所有。请勿转载和采集!