函数 partitionSelect #
基于分区的数组或一维矩阵选择。将找到第 k 小的值,并修改输入数组。使用 Quickselect。
Syntax #
math.partitionSelect(x, k)
math.partitionSelect(x, k, compare)
Parameters #
| Parameter | Type | Description |
|---|---|---|
x |
矩阵 | 数组 | 要排序的一维矩阵或数组 |
k |
Number | 要检索的第 k 小的值,零基索引 |
compare |
函数 | ‘asc’ | ‘desc’ | 一个可选的比较器函数。该函数被调用为 compare(a, b),当 a > b 时必须返回 1,当 a < b 时必须返回 -1,当 a == b 时必须返回 0。默认值:“asc”。 |
Returns #
| Type | Description |
|---|---|
| * | 返回第 k 小的值。 |
Throws #
Type | Description —- | ———–
Examples #
math.partitionSelect([5, 10, 1], 2) // returns 10
math.partitionSelect(['C', 'B', 'A', 'D'], 1, math.compareText) // returns 'B'
function sortByLength (a, b) {
return a.length - b.length
}
math.partitionSelect(['Langdon', 'Tom', 'Sara'], 2, sortByLength) // returns 'Langdon'
// the input array is mutated
arr = [5, 2, 1]
math.partitionSelect(arr, 0) // returns 1, arr is now: [1, 2, 5]
math.partitionSelect(arr, 1, 'desc') // returns 2, arr is now: [5, 2, 1]