Ai
1 Star 0 Fork 0

fortunely/LeetCode_CPP

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
QuickSort.cpp 1.82 KB
一键复制 编辑 原始数据 按行查看 历史
fortunely 提交于 2022-05-31 00:29 +08:00 . (chore)匹配Windows平台MSVC
//
// Created by Martin on 2022/4/8.
//
#ifdef __GUNC__
#include <bits/stdc++.h>
#else
#include <vector>
#include <iostream>
#include <random>
#endif // __GUNC__
using namespace std;
//------------------------------------------------
// 快速排序
class QuickSort {
public:
// 对A[p..r]进行排序, 小->大
static void quickSort(vector<int>& A, int p, int r) {
if (p < r) {
// 对A[p, r]进行一次划分, 找枢轴位置q
int q = partition(A, p, r);
if (p < q)
quickSort(A, p, q - 1);
if (q < r)
quickSort(A, q + 1, r);
}
}
// 对A[p..r]进行一次划分, 枢轴位置q.
// 满足A[p..q-1] <= A[q] <= A[q+1..r]
static int partition(vector<int>& A, int p, int r) {
int x = A[r];
int i = p - 1;
for (int j = p; j < r; ++j) {
if (A[j] <= x) {
++i;
std::swap(A[i], A[j]);
}
}
std::swap(A[i + 1], A[r]);
return i + 1;
}
static int partition_2(vector<int>& A, int p, int r) {
int pivot = A[p];
int low = p, high = r;
while (low < high) {
while (low < high && A[high] >= pivot) { --high; }
A[low] = A[high];
while (low < high && A[low] <= pivot) { ++low; }
A[high] = A[low];
}
A[low] = pivot;
return low;
}
};
//------------------------------------------------
// 测试
void print_vector(vector<int>& vec) {
cout << "{";
for (int i = 0; i < vec.size(); ++i) {
cout << vec[i];
if (i < vec.size() - 1) {
cout << ", ";
}
}
cout << "}" << endl;
}
int main()
{
// 生成 TestCase
default_random_engine e;
uniform_int_distribution<int> u(1, 100);
const int kTestNum = 50;
vector<int> vec;
for (int i = 0; i < kTestNum; ++i) {
vec.push_back(u(e));
}
// 打印 TestCase
cout << "origin vector=";
print_vector(vec);
// 堆排序
QuickSort::quickSort(vec, 0, vec.size() - 1);
cout << "after quicksort, vector=";
print_vector(vec);
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/fortunely/leetcode_cpp.git
git@gitee.com:fortunely/leetcode_cpp.git
fortunely
leetcode_cpp
LeetCode_CPP
master

搜索帮助