C++快速排序法代码怎么写

   2025-02-13 9660
核心提示:下面是一个示例的C++快速排序算法的代码:#include iostreamusing namespace std;// 交换两个元素的值void swap(int* a, int* b)

下面是一个示例的C++快速排序算法的代码:

#include <iostream>using namespace std;// 交换两个元素的值void swap(int* a, int* b) {    int temp = *a;    *a = *b;    *b = temp;}// 将数组划分为两个子数组,小于pivot的放在左边,大于pivot的放在右边int partition(int arr[], int low, int high) {    int pivot = arr[high];  // 选择最右边的元素作为pivot    int i = low - 1;    for (int j = low; j <= high - 1; j++) {        if (arr[j] < pivot) {            i++;            swap(&arr[i], &arr[j]);        }    }    swap(&arr[i + 1], &arr[high]);    return i + 1;}// 快速排序函数void quickSort(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(int arr[], int size) {    for (int i = 0; i < size; i++) {        cout << arr[i] << " ";    }    cout << endl;}int main() {    int arr[] = { 8, 3, 6, 2, 1, 5, 7, 4 };    int size = sizeof(arr) / sizeof(arr[0]);    cout << "原数组:";    printArray(arr, size);    quickSort(arr, 0, size - 1);    cout << "排序后:";    printArray(arr, size);    return 0;}

这段代码首先定义了一个用于交换两个元素的函数swap,然后定义了一个用于将数组划分为两个子数组的函数partition,最后定义了一个快速排序函数quickSortquickSort函数在递归调用中对左右子数组进行快速排序,而partition函数则根据选定的pivot将数组进行划分。

在主函数main中,首先定义了一个待排序的数组arr,然后调用quickSort函数进行快速排序,最后调用printArray函数打印排序后的数组。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言