插入排序获取索引?
我使用以下算法进行插入排序:
def insertionSort(A):
indices = [z for z in xrange(len(A))]
for j in range(1, len(A)):
key = A[j]
i = j-1
while (i>=0) and (A[i]<key):
A[i+1] = A[i]
indices[j-i-1] = i+1
i = i-1
A[i+1] = key
但是,我需要维护一个列表以将 A 的原始值的索引映射到 A 的排序值,这意味着如果我有一个 [1,3,4,2 ] 对列表进行排序后 = [4,3,2,1] 我将得到一个索引列表 [3,1,0,2]。
有什么指点吗?我有点卡住了。
已编辑:抱歉,按降序排序..
I use the following algorithm for insertion sort:
def insertionSort(A):
indices = [z for z in xrange(len(A))]
for j in range(1, len(A)):
key = A[j]
i = j-1
while (i>=0) and (A[i]<key):
A[i+1] = A[i]
indices[j-i-1] = i+1
i = i-1
A[i+1] = key
However, I need to maintain a list to map the indices of the original values of A to the sorted values of A, which means if I have a list of [1,3,4,2] after sorting the list = [4,3,2,1] i will have a indices list of [3,1,0,2].
Any pointers? I'm kinda stuck.
EDITED: apologies, sorting in descending order..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
你为什么要写一个排序?使用Python 的内置排序。
Why are you writing a sort? Use Python's builtin sorting.
对 NullUserException 答案的修复很简单:
只需用排序算法替换对排序的调用即可。
the fix to NullUserException's answer is simple:
just replace the call to sorted with your sorting algorithm.
当你设置
A[i+1]=key
时,明确indices[j]=i+1
。但是,当您设置A[i+1]=A[i]
时,您必须递增indices
中具有值i
(因为A
中位于i
的元素现在位于i+1
)。不幸的是,我认为在最坏的情况下,该算法的简单实现将是 O(n^3)。When you set
A[i+1]=key
, clearlyindices[j]=i+1
. However, when you setA[i+1]=A[i]
You must increment the value of the element ofindices
that has the valuei
(because the element ofA
that was ati
is now ati+1
). Unfortunately, I think the naive implementation of this algorithm will be O(n^3) in the worst case.看来您在更改原始数组的同时更改索引数组以跟踪它们的想法应该可行。我发现,当我有时无法同时跟踪两个索引时,我经常会通过单步执行纸上的循环来找出哪里出错了。
Seems like your idea of changing the indices array while changing the original in order to keep track of them should work. I find that when I sometimes have trouble tracking two indices at once and I'll often resort to stepping through the loop(s) on paper to figure out where I'm going wrong.
我稍微修改了你的版本。现在,它对列表 A 进行就地排序(非降序)并返回带有“排序索引”的列表。
I modified your version slightly. It now sorts the list A in place (non descending) and returns a list with the "sorted indices".
我试图解决同样的问题,但我正在对数组而不是列表进行排序。使用排序的问题是它返回一个列表,对于我的目的而言,它占用了太多内存。幸运的是,您可以使用数组和 argsort 使用 numpy 来完成此操作:
这将给出 array([0,3,1,2]) 作为结果。这是从低到高排序的。
I was trying to solve the same problem, but I was sorting arrays rather than lists. The problem with using sorted was that it returns a list, which for my purposes took up too much memory. Luckily, you can do this with numpy using arrays and argsort:
Which will give array([0,3,1,2]) as a result. This is sorted low to high.