排序:返回一个包含每个元素的新位置的数组

时间:2012-10-16 17:08:06

标签: algorithm sorting

我需要对数组进行排序,同时返回一个包含原始元素的排序位置的数组。 (N.B.不是argsort,用于对数组进行排序的索引)

目前这需要两个步骤:

  1. 一个argsort
  2. 对新阵列的分散操作 即pos [argsort [i]] = i
  3. 我觉得我在这里错过了一招。这是一个众所周知的算法,我忽略了一步可以实现吗?

    步骤2也可以通过搜索实现,但我认为分散效率更高。

    我已经包含了一些示例python代码来说明问题。

    import numpy as np
    
    l = [0,-8,1,10,13,2]
    
    a = np.argsort(l)
    # returns [1 0 2 5 3 4], the order required to sort l
    
    # init new list to zero
    pos = [0 for x in range(0,len(l))]
    
    # scatter http://en.wikipedia.org/wiki/Gather-scatter_(vector_addressing)
    for i in range(0,len(l)):
            pos[a[i]] = i
    
    print pos
    # prints [1, 0, 2, 4, 5, 3], i.e. each original indexes new position in the sorted array
    

    搜索此问题的引用让我感到沮丧,也许我错过了这种操作的正确术语。

    非常感谢任何帮助或指导。

1 个答案:

答案 0 :(得分:0)

这是一个简单的实现,虽然它没有任何有意义的“就地”。我不确定“就地”是什么意思,因为输出是int类型的np.array,输入可能包含双精度。

更新以回应@ norio的评论并澄清意图:

#!/usr/bin/env python

import numpy as np

unsorted = np.array([0,-8,1,10,13,2])

def myargsort(numbers):
  tuples = enumerate(numbers) # returns iterable of index,value
  sortedTuples = sorted(tuples,key = lambda pair: pair[1])
  sortedNumbers = [num for idx,num in sortedTuples]
  sortIndexes   = [idx for idx,num in sortedTuples]
  return (sortedNumbers,sortIndexes)

sortedNums, sortIndices = myargsort(unsorted)

print(unsorted)
print(sortedNums)
print(sortIndices)