简体   繁体   English

在Scala中将元素插入有序数组的最佳方法

[英]Best way to insert an element into an ordered array in Scala

I have an Array, or Seq looks like 我有一个数组,或者Seq看起来像

val myArray = collection.mutable.ArrayBuffer[Int](1,4,8,10,12,13)

val newElem = 7

I want to insert the new element into the Array at the right position, so that the array is still ordered. 我想将新元素插入到Array中的正确位置,以便仍然对数组进行排序。

I don't want to generate a new array here. 我不想在这里生成一个新数组。

My solution is to find the insert position first, and then insert it. 我的解决方案是先找到插入位置,然后再插入。

def findInsertPosition(myArray: collection.multable.ArrayBuffer[Int], newElem: Int): Int

then call 然后打电话

myArray.insert(pos, newElem)

The question is how to write the findInsertPosition function in Scala style, without using while, for loops? 问题是如何以Scala样式编写findInsertPosition函数,而不使用while,for循环?

or if you have better solution? 还是您有更好的解决方案?

Find the insert position with lastIndexWhere and add one to it then insert at that position. 使用lastIndexWhere查找插入位置,然后向其添加一个,然后在该位置insert

scala> val xs = scala.collection.mutable.ArrayBuffer(1,4,8,10,12,13)
xs: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 4, 8, 10, 12, 13)

scala> xs.insert(xs.lastIndexWhere(_ < 7) + 1, 7)

scala> xs
res10: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 4, 7, 8, 10, 12, 13)

This might be a bit inefficient, but it works: 这可能有点效率低下,但可以:

def findInsertPosition(myArray: collection.mutable.ArrayBuffer[Int], newElem: Int): Int =
  myArray.takeWhile(_ < newElem).size

It will be the correct index when inserting. 插入时它将是正确的索引。

The first thing that comes to my mind: 我想到的第一件事是:

myArray.insert(
  Stream.range(0, myArray.length)
    .find(a(_) >= newElem)
    .getOrElse(myArray.length), 
  newElem)

another approach would be something similar to Brian's answer 另一种方法将类似于布莱恩的答案

myArray.insert(
  myArray.indexWhere(_ >= newElem),
  newElem)

Find the correct index point and insert. 找到正确的索引点并插入。

val idx = myArray.indexWhere(_>newElem)
myArray.insert(if (idx<0) myArray.length else idx, newElem)
// ArrayBuffer(1, 4, 7, 8, 10, 12, 13)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM