我正在尝试将数组划分为两个区域S1& S2。枢轴必须是数组的第一个元素。所以,例如:
7 5 9 2 6
7是支点。
我想拥有S1区域;小于数据透视的数字
S2区域;数字大于枢轴。
像这样:
5 2 6 7 9
如何用C ++语言实现它?
答案 0 :(得分:3)
您可以使用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