8. 快排示例代码: ```cpp #include <iostream> (30316)#include <vector> 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++; 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); quickSort(arr, pi + 1, high); } } int main() { std::vector<int> arr = {8, 4, 2, 7, 1, 5, 9}; int n = arr.size(); quickSort(arr, 0, n - 1); std::cout << "Sorted array:"; for (auto num : arr) { std::cout << " " << num; } std::cout << std::endl; return 0; } ```
点赞 评论

相关推荐

牛客网
牛客企业服务