是否有一个包含`argsort`实现或包装器的Nim库?

时间:2016-04-25 03:23:11

标签: sorting nim

我正在寻找argsort的版本,例如as exists in numpyin fortran。在Nim中是否有argsort的实现...或者某些库中的Nim可以访问?它缺失了似乎有点令人惊讶。

更新

以下内容似乎适用于argsort

proc argsort[T](a : T) : seq[int] =
  result = toSeq(0..a.len - 1)
  sort(result, proc (i, j: int): int = cmp(a[i], a[j]))

据推测,它本身可以更有效地编写并避免使用函数指针....

1 个答案:

答案 0 :(得分:2)

它还没有变得敏捷,但是Arraymancer有一个argsort here

import arraymancer,algorithm,sequtils

proc argsort*[T](t: Tensor[T], order = SortOrder.Ascending): Tensor[int] =
  ## Returns the indices which would sort `t`. Useful to apply the same sorting to
  ## multiple tensors based on the order of the tensor `t`.
  ##
  ## Sorts the raw underlying data!
  # TODO: should we clone `t` so that if `t` is a view we don't access the whole
  # data?
  assert t.rank == 1, "Only 1D tensors can be sorted at the moment!"
  proc cmpIdxTup(x, y: (T, int)): int = system.cmp(x[0], y[0])
  # make a tuple of input & indices
  var tups = zip(toOpenArray(t.storage.Fdata, 0, t.size - 1),
                 toSeq(0 ..< t.size))
  # sort by custom sort proc
  tups.sort(cmp = cmpIdxTup, order = order)
  result = newTensorUninit[int](t.size)
  for i in 0 ..< t.size:
    result[i] = tups[i][1]

let x = @[3,9,4,1,5].toTensor()

echo x.argsort()

产生:

Tensor[system.int] of shape [5]" on backend "Cpu"
    3   0   2   4   1

try it out here