划分有关枢轴C 的数组

Partitioning an array about a pivot C++

本文关键字:数组 划分      更新时间:2023-10-16

我试图将数组分为两个区域S1&S2。枢轴必须是数组的第一个元素。因此,例如:

7 5 9 2 6

7是枢轴。

我想拥有S1区域;小于枢轴

的数字

S2区域;比枢轴大的数字。

这样:

5 2 6 7 9

如何以C 语言实现此功能?

您可以使用std::stable_partition

#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
    std::vector<int> v{7,5,9,2,6};
    std::stable_partition(v.begin(), v.end(), [x=v[0]](int n){return n<x;});
    for (int n : v) {
        std::cout << n << ' ';
    }
    std::cout << 'n';
}

输出

5 2 6 7 9

demo