温馨提示×

c++快速排序算法的代码怎么写

c++
小亿
82
2024-03-12 14:09:39
栏目: 编程语言

#include <iostream>
#include <vector>

void quickSort(std::vector<int>& arr, int low, int high) {
    if (low < high) {
        int pivot = arr[low];
        int i = low + 1;
        int j = high;

        while (i <= j) {
            if (arr[i] <= pivot) {
                i++;
            } else if (arr[j] > pivot) {
                j--;
            } else {
                std::swap(arr[i], arr[j]);
            }
        }

        std::swap(arr[low], arr[j]);

        quickSort(arr, low, j - 1);
        quickSort(arr, j + 1, high);
    }
}

int main() {
    std::vector<int> arr = {5, 2, 9, 3, 7, 1, 8, 4, 6};
    quickSort(arr, 0, arr.size() - 1);

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

    return 0;
}

这段代码实现了快速排序算法,对一个整数数组进行排序。通过递归地将数组分为两部分,然后对各自的部分进行排序,最终得到一个有序的数组。在主函数中,我们定义一个整数数组并调用quickSort函数对其进行排序,然后输出排序后的结果。

0