对索引集合(排序的索引序列)进行二分搜索
我有一个A
类型的索引集合(必须已索引):
var coll: IndexedSeq[A]
我希望根据某些排序保持
但我经常向其中添加/删除项目。执行此操作的明显机制类似于:coll
排序[A]
def binarySearch[A : Ordering](a: IndexedSeq[A], elem: A): Int
def add(a: A) {
val idx = binarySearch(coll, a)
coll = (coll take idx) :+ a +: (coll drop idx)
}
但是标准库中既没有 binarySearch
(奇怪,因为有 scala.util.Sorting.quickSort
)并且我找不到既可以索引又可以排序的数据类型(我猜这是一个低效的结构)。
I have an indexed collection (it must be indexed) of some type A
:
var coll: IndexedSeq[A]
I wish to keep coll
sorted according to some Ordering[A]
but I am frequently adding/removing items to/from it. The obvious mechanism to do this is something like:
def binarySearch[A : Ordering](a: IndexedSeq[A], elem: A): Int
def add(a: A) {
val idx = binarySearch(coll, a)
coll = (coll take idx) :+ a +: (coll drop idx)
}
But there is neither a binarySearch
in the standard library (odd, seeing as there is scala.util.Sorting.quickSort
) and there is no datatype I can find that is both indexed and sorted (I guess that this is an inefficient structure).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为
TreeSet
上的slice
相当有效(并且您可以将它与单元素范围一起使用),但您是对的 - 没有索引很奇怪排序的数据结构。而且效率足够高;如果跟踪子级的数量,则大多数排序树都可以以这种方式使用。我认为这只是一个疏忽,它的缺失。如果您使用仅允许引用相等的标记包装重复元素,则始终可以对它们使用集合,并且可以确保它们是有序的:
但是,对于相对简单的任务,这确实会增加大量开销。
I think
slice
onTreeSet
is reasonably efficient (and you can use it with a one-element range), but you're right--it's strange that there is no indexed sorted data structure. And it's efficient enough; most any sorted tree can be used that way if the number of children are tracked. I think it's just an oversight that it's missing.You can always use a set for repeated elements if you wrap them with a tag that only allows reference equality, and you can make sure they're ordered:
This does add a lot of overhead for a comparatively simple task, however.
http://www.scala-lang.org /api/2.11.4/index.html#scala.collection.Searching$$SearchImpl
http://www.scala-lang.org/api/2.11.4/index.html#scala.collection.Searching$$SearchImpl
}
}