#include <iostream>
#include <vector>
int partition(std::vector<int>& array, int low, int high) {
int pivot = array[high]; // take last element as pivot
int i = low - 1; // index of smaller element
for (int j = low; j <= high - 1; ++j) {
if (array[j] < pivot) { // if element is smaller than pivot
i++;
std::swap(array[i], array[j]);
}
}
std::swap(array[i + 1], array[high]);
return i + 1;
}
void quickSort(std::vector<int>& array, int low, int high) {
if (low < high) {
int pi = partition(array, low, high);
quickSort(array, low, pi - 1);
quickSort(array, pi + 1, high);
}
}
void print1DVecter(std::vector<int>& array) {
for (auto arr: array) {
std::cout << arr << " ";
}
std::cout << '\n';
}
int main()
{
std::vector<int> array {10, 7, 8, 9, 1, 5};
std::cout << "Before sort: ";
print1DVecter(array);
quickSort(array, 0, array.size() - 1);
std::cout << "after sort: ";
print1DVecter(array);
return 0;
}
C++ 快速排序
最新推荐文章于 2024-03-01 18:39:10 发布