I am trying to implement the searchsorted algorithm(side=right) in scala that is, find last index where an element should be inserted in order to maintain the sorting order.
For ex.
val arr = List(1,2,2,3,4,4,6,6). // assume list is sorted, also array can have negetive elements(albeit sorted)
if elem = 2, output index = 3
if elem = 3, output index = 4
if elem = 5, output index = 6
if elem = -3, output index = 0
I came up with this, iterating through each element in the list, and checking the smallest diff
val a = List(1,1,2,2,3,3,4,5,5)
val elem = 1
val (_, index) = a
.foldLeft(Int.MaxValue, 0) {
case ((smallestDiff, index), currNum) =>
val currDiff = (elem - currNum).abs
if (currDiff > smallestDiff) (smallestDiff, index)
else (currDiff, index + 1)
}
This one works fine for 1st 2 examples, but completely breaks for last 2 ex