分区之后枢轴落在哪

👁️ 1 人浏览 💬 0 人评论 ❤️ 添加收藏

以最后一个(23)为枢轴给 17 24 15 13 23 分区。

运行下面这段程序:

#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>
using namespace std;

int part_last(vector<int>& b) {
    // 以最后一个为枢轴:比它小的挪到左边,返回枢轴最终的下标
    int n = (int)b.size();
    int pivot = b[n - 1];
    int i = 0;
    for (int j = 0; j < n - 1; j++) {
        if (b[j] < pivot) {
            swap(b[i], b[j]);
            i++;
        }
    }
    swap(b[i], b[n - 1]);
    return i;
}

int main() {
    vector<int> b = {17, 24, 15, 13, 23};
    cout << part_last(b) << endl;
}

(本题用 g++ -std=c++17 -O0 编译。)

提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论
🔒 登录并作答后可看讨论