Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala replacement for Arrays.binarySearch?

Is there a replacement in Scala for Java's int Arrays.binarySearch(Object[] array, object)?

The problem is that Scala's Arrays are not covariant, so I would have to cast my stringArray: Array[String] like this first:

stringArray.asInstanceOf[Array[Object]] 

Is there a better solution?

like image 975
soc Avatar asked Nov 19 '10 16:11

soc


People also ask

What arrays return Binarysearch?

Returns. The index of the specified value in the specified array , if value is found; otherwise, a negative number. If value is not found and value is less than one or more elements in array , the negative number returned is the bitwise complement of the index of the first element that is larger than value .

Is there array in Scala?

Scala provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.


1 Answers

Scala 2.11 added scala.collection.Searching to the standard library. It uses binary search for indexed sequences and linear search otherwise.

import scala.collection.Searching._ Array(1, 2, 3, 4, 5).search(3) 
like image 67
Joe Pallas Avatar answered Oct 07 '22 19:10

Joe Pallas