使用容器c++完成快速排序应用
下面是使用C++容器实现快速排序的示例代码:
#include <iostream>
#include <vector>
using namespace std;
int partition(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++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return i + 1;
}
void quickSort(vector<int>& arr, int low, int high) {
if (low < high) {
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
void printArray(const vector<int>& arr) {
for (int num : arr) {
cout << num << " ";
}
cout << endl;
}
int main() {
vector<int> arr = {9, 5, 7, 1, 3, 10, 2, 6, 8, 4};
int n = arr.size();
cout << "Original array: ";
printArray(arr);
quickSort(arr, 0, n - 1);
cout << "Sorted array: ";
printArray(arr);
return 0;
}
这个程序首先定义了一个partition函数,用于将数组分成两部分,并返回分割点的索引。然后,quickSort函数使用递归的方式对分割后的子数组进行排序。最后,printArray函数用于打印数组的内容。
程序的输出结果为:
Original array: 9 5 7 1 3 10 2 6 8 4
Sorted array: 1 2 3 4 5 6 7 8 9 10
``
原文地址: http://www.cveoy.top/t/topic/iUy0 著作权归作者所有。请勿转载和采集!