简体   繁体   English

根据条件划分数组中的元素

[英]Dividing elements in the array against a condition

As far as I remember it was called(3,4 years ago) partition step and it was part of a quicksort but I am not sure. 据我记得它被称为(3,4年前)分区步骤,它是快速排序的一部分,但我不确定。

I have to spllt element in the array against a condition for instance condition: x < 5 我必须针对例如条件的条件spllt数组中的元素:x <5

For array: 对于数组:

7,2,7,9,4,2,8

The result would be: 结果将是:

2,4,2,7,7,8,9 

The order of the elements does not matter. 元素的顺序无关紧要。 It supposed to be done within one for loop without embeded for loops inside. 它应该在一个for循环中完成,而不是内部循环嵌入。

I am looking for a pseudo or c++ code for how to swap elements against that kind of "pivot" condtiion. 我正在寻找一个伪或c ++代码,用于如何交换元素与这种“枢轴”条件。

The code I've already managed to create: 我已经设法创建的代码:

#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <functional>
using namespace std;

template <typename T>

size_t partition(T arr[], size_t size, function<bool(T)> fun) {
    //here I would like to split it against the fun():boolean result
    return 4;
}

template <typename T>
void printTable(T arr[], size_t size) {
    for (int i = 0; i < size; i++)
        cout << arr[i] << " ";
    cout << endl;
}

template <typename T> bool less10(T a) {
    return a < 10;
}
int main(){
    cout << "BLABLA" << endl;
    int arri[] = { 1, 20, 3, 50, 6, 7 };
    size_t sizi = sizeof(arri) / sizeof(arri[0]); printTable(arri, sizi);
    size_t fi = partition(arri, sizi, (function<bool(int)>)less10<int>);
    printTable(arri, sizi);
    cout << "index: " << fi << endl; cout << endl;
    double arrd[] = { 1, 20, 3, 50, 6, 7 };
    size_t sizd = sizeof(arrd) / sizeof(arrd[0]); printTable(arrd, sizd); function<bool(double)> lambda =
        [](double x) -> bool {return x > 10; }; size_t fd = partition(arrd, sizd, lambda); printTable(arrd, sizd);
    cout << "index: " << fd << endl;
    system("PAUSE");
    return 0;
}

You could code it like so 你可以像这样编码

#include <algorithm>

int main()
{
    int ar[] = {7,2,7,9,4,2,8};

    std::partition(std::begin(ar), std::end(ar), [](int val) {
        return val < 5; });
}

If implementation of std::partition is what matters you could check a trivial implementation 如果std :: partition的实现是重要的,那么你可以检查一个简单的实现

template <class BidirectionalIterator, class UnaryPredicate>
BidirectionalIterator partition (BidirectionalIterator first, BidirectionalIterator last, UnaryPredicate pred)
{
  while (first!=last) {
    while (pred(*first)) {
      ++first;
      if (first==last) return first;
    }
    do {
      --last;
      if (first==last) return first;
    } while (!pred(*last));
    swap (*first,*last);
    ++first;
  }
  return first;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM