c++20实现快速排序
以下是使用C++20实现快速排序的示例代码:
#include <iostream>
#include <vector>
#include <algorithm>
template<typename T>
void quickSort(std::vector<T>& arr, int left, int right) {
if (left < right) {
T pivot = arr[(left + right) / 2];
int i = left - 1;
int j = right + 1;
while (true) {
do {
i++;
} while (arr[i] < pivot);
do {
j--;
} while (arr[j] > pivot);
if (i >= j)
break;
std::swap(arr[i], arr[j]);
}
quickSort(arr, left, j);
quickSort(arr, j + 1, right);
}
}
int main() {
std::vector<int> arr = {5, 2, 9, 3, 7, 6, 1, 8, 4};
quickSort(arr, 0, arr.size() - 1);
for (int i : arr) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
在上面的代码中,我们使用了C++20中的std::vector容器来存储排序的数组。quickSort函数采用了传统的快速排序算法,它的主要思路是将数组划分为两个部分,左边部分的元素都比右边部分的元素小。我们以数组中间的元素为基准点(pivot)进行划分,然后递归地对左右两个部分进行排序。在实现过程中,我们使用了C++20中的std::swap函数来交换数组中的元素。
在main函数中,我们首先定义了一个包含九个整数的数组,并将其传递给quickSort函数进行排序。最后,我们使用一个循环遍历已排序的数组,并将其输出到标准输出流中。
原文地址: https://www.cveoy.top/t/topic/sFf 著作权归作者所有。请勿转载和采集!