Instance Method インスタンスメソッド

partition(by:)

Reorders the elements of the collection such that all the elements that match the given predicate are after all the elements that don’t match. コレクションの要素を再配列します、例えば、与えられた述部にマッチする要素すべてが、合致しない要素すべての後になるなど。

Declaration 宣言

mutating func partition(by belongsInSecondPartition: (Element) throws -> Bool) rethrows -> Int

Parameters パラメータ

belongsInSecondPartition

A predicate used to partition the collection. All elements satisfying this predicate are ordered after all elements not satisfying it. コレクションに仕切りをするのに使われる述部。この述部を満たす全ての要素は、それを満たさない全ての要素の後に並べられます。

Return Value 戻り値

The index of the first element in the reordered collection that matches belongsInSecondPartition. If no elements in the collection match belongsInSecondPartition, the returned index is equal to the collection’s endIndex. 並べ直されたコレクションの中の最初の要素のインデックス、それはbelongsInSecondPartitionに合致します。コレクションの中の要素が1つもbelongsInSecondPartitionに一致しないならば、返されるインデックスはコレクションのendIndexと等しいです。

Discussion 解説

After partitioning a collection, there is a pivot index p where no element before p satisfies the belongsInSecondPartition predicate and every element at or after p satisfies belongsInSecondPartition. コレクションを仕切った後、あるピボットインデックスpがあります、そこでpの前の要素は1つもbelongsInSecondPartition述部を満たさず、そしてpでのまたは後のあらゆる要素はbelongsInSecondPartitionを満たします。 This operation isn’t guaranteed to be stable, so the relative ordering of elements within the partitions might change.

In the following example, an array of numbers is partitioned by a predicate that matches elements greater than 30. 次の例において、数からなる配列は、30より大きな要素に合致するという述部によって仕切られます。


var numbers = [30, 40, 20, 30, 30, 60, 10]
let p = numbers.partition(by: { $0 > 30 })
// p == 5
// numbers == [30, 10, 20, 30, 30, 60, 40]

The numbers array is now arranged in two partitions. The first partition, numbers[..<p], is made up of the elements that are not greater than 30. The second partition, numbers[p...], is made up of the elements that are greater than 30. numbers配列は今や2つの区分に整頓されます。最初の区画、numbers[..<p]は、30より大きくない要素から構成されます。2番目の区画、numbers[p...]は、30より大きなものである要素から構成されます。


let first = numbers[..<p]
// first == [30, 10, 20, 30, 30]
let second = numbers[p...]
// second == [60, 40]

Note that the order of elements in both partitions changed. That is, 40 appears before 60 in the original collection, but, after calling partition(by:), 60 appears before 40.

Complexity: O(n), where n is the length of the collection. 計算量:O(n)、ここでnはコレクションの長さです。

See Also 参照

Reordering an Array's Elements 配列の要素を再配列します