C++用STL的容器vector和算法partition实现快速排序功能
时间: 2024-02-21 21:01:38 浏览: 94
下面是使用STL的vector和算法partition实现快速排序的C++代码:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
// 快速排序函数
void quickSort(std::vector<int>& nums, int low, int high) {
if(low >= high) return; // 数组中只有一个元素或者没有元素
int pivot = nums[low]; // 以第一个元素为基准
int i = low + 1, j = high;
while(i <= j) {
while(i <= j && nums[i] < pivot) i++; // 找到第一个大于等于基准的元素
while(i <= j && nums[j] >= pivot) j--; // 找到第一个小于基准的元素
if(i < j) std::swap(nums[i], nums[j]); // 交换这两个元素
}
std::swap(nums[low], nums[j]); // 将基准元素放到正确的位置上
quickSort(nums, low, j - 1); // 递归处理左边的子数组
quickSort(nums, j + 1, high); // 递归处理右边的子数组
}
int main() {
std::vector<int> nums{4, 2, 8, 5, 1, 3, 9, 6, 7};
std::cout << "Before sorting: ";
for(int num : nums) std::cout << num << " ";
std::cout << std::endl;
std::cout << "After sorting: ";
quickSort(nums, 0, nums.size() - 1);
for(int num : nums) std::cout << num << " ";
std::cout << std::endl;
return 0;
}
```
在上面的代码中,我们使用vector来存储需要排序的数组,使用partition算法将数组分成两个部分,然后递归地对这两个部分进行排序,最终得到排序后的数组。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20210720083447.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)