【问题标题】:Writing a function for arranging the elements in an array编写用于排列数组中元素的函数
【发布时间】:2020-02-27 10:53:12
【问题描述】:

目的是将数组的元素从左侧的正数和右侧的负数排列。约束是只能使用一个数组。此外,元素出现的顺序在排列的输出数组中应该保持不变。 样本输入

10(数组中的元素数) -6 7 13 10 -8 15 5 -9 2 -1(数组元素) 样本输出

7 13 10 15 5 2 -6 -8 -9 -1

【问题讨论】:

  • std::stable_partition 正是针对这种情况而设计的。
  • 既然你是新来的,你应该看看这个:softwareengineering.meta.stackexchange.com/questions/6166/…
  • @user3386109:这不是一个稳定的排序,而是一个稳定的分区。为什么编程语言很重要?
  • 使用快速排序(查找算法),它只使用一个数组。
  • @Rhnbmpl 快速排序不稳定。尽管您可以修改 Quicksort 以使其稳定,但这是矫枉过正的。问题是对数组进行partition,而不是对其进行sort。分区是一个 O(n) 操作。排序是 O(n log n)。

标签: c++ c algorithm function


【解决方案1】:

您需要以稳定的方式分区数组的元素。正如评论中已经建议的那样,您可以使用std::stable_partition 函数模板:

template<class BidirIt, class UnaryPredicate>
BidirIt stable_partition(BidirIt first, BidirIt last, UnaryPredicate p);

[first, last) 范围内的元素重新排序,使得 谓词 p 返回的所有元素 true 位于 谓词p 返回false 的元素。的相对顺序 元素被保留。

举个例子:

#include <vector>
#include <algorithm>
#include <iostream>

auto main() -> int {
   std::vector<int> v{0, -1, -7, 3, 5, -9, 2};

   // predicate for partitioning
   auto pred = [](int x) {
      return x >= 0;
   };

   std::stable_partition(v.begin(), v.end(), pred);

   for (auto i: v)
      std::cout << i << ' ';
   std::cout << '\n';
}

输出是:

0 3 5 2 -1 -7 -9 

谓词pred 为属于第一组的元素(即非负元素)返回true,为属于第二组的元素(即负元素)返回false

请注意,std::stable_partitionstd::partition 都会返回指向第二组第一个元素的迭代器,以防您想知道组边界。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-22
    • 2013-01-27
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    相关资源
    最近更新 更多