快排 C++

100 20 10 7 8 9 1 5 6 3 2 4

1 3 2 4 8 9 100 5 6 20 10 7

1 3 2

1 2 3

8 9 100 5 6 20 10 7

5 6 7 8 9 20 10 100

5 6

5 6

8 9 20 10 100

8 9 20 10 100

8 9 20 10

8 9 10 20

8 9

8 9

Sorted array:

1 2 3 4 5 6 7 8 9 10 20 100
PS F:\BC\2024\9\28> ./Main7

100 20 10 7 8 9 1 5

1 5 10 7 8 9 100 20

10 7 8 9 100 20

10 7 8 9 20 100

10 7 8 9

7 8 9 10

7 8

7 8

Sorted array:

1 5 7 8 9 10 20 100

cpp 复制代码
#include<iostream>
using namespace std;

void printArray(int arr[], int low, int high) {
    for (int i = low; i <= high; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;        
}

int partition(int arr[], int low, int high) {    
    printArray(arr,low,high);
    int pivot = arr[high];// 选择最后一个元素作为基准
    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]); // 将基准放到正确的位置
    printArray(arr,low,high);
    cout<<endl;
    return (i + 1);//返回基准的最终位置
}

void quickSort(int arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);// 获取分区点
        quickSort(arr, low, pi - 1);// 递归排序左子数组
        quickSort(arr, pi + 1, high);// 递归排序右子数组
    }
}

int main() {
    int arr[] = { 100,20,10, 7, 8, 9, 1, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
    //printArray(arr, 0, n - 1);
    quickSort(arr, 0, n - 1);
    cout << "Sorted array: \n";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    return 0;
}
相关推荐
GG不是gg几秒前
排序算法之基础排序:冒泡,选择,插入排序详解
数据结构·算法·青少年编程·排序算法
随意起个昵称22 分钟前
【双指针】供暖器
算法
倒霉蛋小马26 分钟前
最小二乘法拟合直线,用线性回归法、梯度下降法实现
算法·最小二乘法·直线
codists1 小时前
《算法导论(第4版)》阅读笔记:p82-p82
算法
埃菲尔铁塔_CV算法1 小时前
深度学习驱动下的目标检测技术:原理、算法与应用创新
深度学习·算法·目标检测
float_com1 小时前
【背包dp-----分组背包】------(标准的分组背包【可以不装满的 最大价值】)
算法·动态规划
丶Darling.2 小时前
Day119 | 灵神 | 二叉树 | 二叉树的最近共公共祖先
数据结构·c++·算法·二叉树
L_cl3 小时前
【Python 算法零基础 3.递推】
算法
int型码农3 小时前
数据结构第七章(四)-B树和B+树
数据结构·b树·算法·b+树
先做个垃圾出来………4 小时前
汉明距离(Hamming Distance)
开发语言·python·算法