How to write code for Quick Sort in C++?

Below is an example code for the quick sort algorithm in 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;
}

First, this code defines a function called swap for swapping two elements, then it defines a function called partition for dividing the array into two subarrays, and finally defines a quicksort function called quickSort. The quickSort function recursively sorts the left and right subarrays, while the partition function divides the array based on a selected pivot.

In the main function, an array arr is first defined for sorting, then the quickSort function is called for sorting, and finally the printArray function is called to print the sorted array.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds