Created
April 13, 2021 11:33
-
-
Save veevidify/1fb7feeecfb1aa93a2418b263889582e to your computer and use it in GitHub Desktop.
Scala snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.math.Ordering.{String => StringOrdering} | |
import scala.collection.Searching._ | |
import scala.util.Sorting | |
implicit class Search[A, LS](val coll: LS)(implicit ls2idxseq: LS => IndexedSeq[A]) { | |
def binarySearch[B >: A](elem: B, from: Int = 0, to: Int = coll.length) | |
(implicit ord: Ordering[B]): SearchResult = { | |
if (to == from) InsertionPoint(from) else { | |
val idx = from + (to - from - 1) / 2 | |
math.signum(ord.compare(elem, coll(idx))) match { | |
case -1 => binarySearch(elem, from, idx)(ord) | |
case 1 => binarySearch(elem, idx + 1, to)(ord) | |
case _ => Found(idx) | |
} | |
} | |
} | |
} | |
val mySeq = Seq("a", "c", "b", "j", "z").toArray | |
Sorting.quickSort(mySeq)(StringOrdering) | |
Search(mySeq).binarySearch[String]("test") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment