C++ Quicksort Implementation Guide

The quick sort function in C++ can be used by following these steps:

  1. “Include the iostream library.”
  2. Create a quicksort function that takes an array to be sorted, a starting index, and an ending index as parameters.
  3. In the quicksort function, select a pivot element (usually the first element of the array).
  4. Set up two pointers, one pointing to the starting index and one pointing to the ending index.
  5. Place elements smaller than the reference element to the left, and elements larger to the right.
  6. Recursively call the quick sort function to sort the left and right subarrays of the pivot element.
  7. Call the quicksort function outside the quicksort function to sort the array.

Here is an example code using the quick sort function:

#include <iostream>

// 快速排序函数
void quickSort(int arr[], int start, int end) {
    if (start < end) {
        int pivot = arr[start]; // 基准元素
        int i = start; // 左指针
        int j = end; // 右指针

        while (i < j) {
            // 从右往左找到比基准元素小的元素
            while (i < j && arr[j] >= pivot) {
                j--;
            }
            if (i < j) {
                arr[i] = arr[j];
                i++;
            }

            // 从左往右找到比基准元素大的元素
            while (i < j && arr[i] <= pivot) {
                i++;
            }
            if (i < j) {
                arr[j] = arr[i];
                j--;
            }
        }

        arr[i] = pivot; // 将基准元素放到正确的位置

        // 递归调用快速排序函数
        quickSort(arr, start, i - 1); // 对左边的子数组进行排序
        quickSort(arr, i + 1, end); // 对右边的子数组进行排序
    }
}

int main() {
    int arr[] = {5, 2, 8, 3, 1, 6};
    int n = sizeof(arr) / sizeof(arr[0]);

    std::cout << "原始数组:";
    for (int i = 0; i < n; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    quickSort(arr, 0, n - 1); // 调用快速排序函数

    std::cout << "排序后的数组:";
    for (int i = 0; i < n; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}

Output result:

原始数组:5 2 8 3 1 6 
排序后的数组:1 2 3 5 6 8

In the example above, we defined a quickSort function to sort an array quickly. We then called this function in the main function, and outputted the sorted array.

bannerAds