Files
algo2025/sort_closet/code-sorting/QuickSort.cpp
2025-12-18 16:00:22 +08:00

49 lines
1.2 KiB
C++

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int partition(vector<int> &nums, int low, int high, long long &comp_count, long long &move_count)
{
int pivot = nums[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++)
{
comp_count++;
if (nums[j] < pivot)
{
i++;
swap(nums[i], nums[j]);
move_count += 3;
}
}
swap(nums[i + 1], nums[high]);
move_count += 3;
return (i + 1);
}
void quickSortHelper(vector<int> &nums, int low, int high, long long &comp_count, long long &move_count)
{
if (low < high)
{
int pi = partition(nums, low, high, comp_count, move_count);
quickSortHelper(nums, low, pi - 1, comp_count, move_count);
quickSortHelper(nums, pi + 1, high, comp_count, move_count);
}
}
/*
* function : implement quick sort
* param nums : the vector to be sorted
* param comp_count : count of comparisons
* param move_count : count of moves
* return : ---
*/
void QuickSort(vector<int> &nums, long long &comp_count, long long &move_count)
{
if (nums.empty()) return;
quickSortHelper(nums, 0, nums.size() - 1, comp_count, move_count);
}