没有合适的资源?快使用搜索试试~ 我知道了~
快速排序c.docx. // 调用快速排序算法 quickSort(arr)
需积分: 5 0 下载量 133 浏览量
2023-12-09
13:05:40
上传
评论
收藏 11KB DOCX 举报
温馨提示
试读
2页
快速排序c++. int main() { std::vector<int> arr = {12, 7, 11, 9, 3, 5}; std::cout << "Original array: "; for (int num : arr) { std::cout << num << " "; } std::cout << std::endl; // 调用快速排序算法 quickSort(arr); std::cout << "Sorted array: "; for (int num : arr) { std::cout << num << " "; } std::cout << std::endl; return 0; }
资源推荐
资源详情
资源评论
快速排序 c++
#include <iostream>
#include <vector>
// 函数声明
int partition(std::vector<int>& arr, int low, int high);
void quickSort(std::vector<int>& arr, int low, int high);
// 快速排序的主函数
void quickSort(std::vector<int>& arr) {
int low = 0;
int high = arr.size() - 1;
quickSort(arr, low, high);
}
// 分区函数,用于确定枢轴元素的位置
int partition(std::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++;
// 交换 arr[i] 和 arr[j]
std::swap(arr[i], arr[j]);
}
}
// 将枢轴元素放到正确的位置上
std::swap(arr[i + 1], arr[high]);
return i + 1;
}
// 快速排序递归函数
void quickSort(std::vector<int>& arr, int low, int high) {
if (low < high) {
// 找到分区的索引
int pi = partition(arr, low, high);
// 递归地对枢轴左边的子数组进行排序
quickSort(arr, low, pi - 1);
// 递归地对枢轴右边的子数组进行排序
资源评论
常驻客栈
- 粉丝: 1w+
- 资源: 1366
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功