下面是一个使用容器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 pivot = Partition(arr, low, high);

        QuickSort(arr, low, pivot - 1);
        QuickSort(arr, pivot + 1, high);
    }
}

int main() {
    vector<int> arr = {9, 5, 7, 3, 2, 1, 6, 8, 4};

    QuickSort(arr, 0, arr.size() - 1);

    cout << "Sorted array: ";
    for (int num : arr) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}

这段代码使用了一个函数Partition来找到数组的分区点,并且返回此分区点的索引,然后递归地对分区点的左右两个子数组进行排序。最后,在main函数中调用QuickSort函数来完成快速排序。

运行以上代码的输出结果为:

Sorted array: 1 2 3 4 5 6 7 8 9
``
使用容器c++完成快速排序应用只使用一个函数

原文地址: http://www.cveoy.top/t/topic/iUy6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录