如何解决将数字插入有序数组的最有效方法是什么?
将数字插入已排序的数组是非常普遍的需求。
Mathematica堆栈交换以供参考。它的优先级队列显得非常快。 https://mathematica.stackexchange.com/questions/224249/best-way-to-insert-element-into-an-ordered-list-at-the-correct-position
对于J:
使用内置排序/:~y
,其中y
是排序后的数组-
示例:/:~ y,45.3
或/:~ y,3 6 67.7
将是第一选择。
Quicksort和bubbleort慢得多。
对于将数字旋转到已排序列表中的单个插入-
insert=: 4 : 0
NB. insert x into ordered array y
where=: x (< i. 1:) y
z=: (($y)-where)|.(where|.y),x
)
在y=.i.10000000
上比/:~y
快2.5倍
有什么更快的吗?
解决方法
二分搜索I.
是在排序数组中查找元素的最佳选择。
[;.0
是提取子数组的最佳方法。
这些都是非常快的:
y =: i.1e7
100 timespacex'y I. 35'
2.94e_6 896
100 timespacex'(35,: _) ];.0 y'
4.85e_6 1856
瓶颈似乎是要追加新元素,从而将列表复制到新列表中。
100 timespacex'35,~(35,: _) ];.0 y'
0.0368233 1.3422e8
insert=: 4 : 0
NB. insert x into ordered array y
where=: x (< i. 1:) y
z=: (($y)-where)|.(where|.y),x
)
insert2=: 4 : 0
where=: y I. x
NB. z =: where ({.,x,}.) y
z =: (where ];.0 y),((where,: _) ];.0 y)
)
y =: i.1e7
(35 insert y) -: (35 insert2 y)
1
100 timespacex'35 insert y'
0.0745025 2.68437e8
100 timespacex'35 insert2 y'
0.0738203 2.68437e8
其他更复杂的方法可能会提供更好的结果,具体取决于您的需求和输入的内容。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。