Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
def binarySearch(list: List[Int], item: Int): Int = {
if(list.isEmpty) { println("Item not found"); return 0 }
val guessIndex = (list.length) / 2
val guess = list(guessIndex)
if(item == guess) guess
else if(item < guess){
val halfList = list.take(list.length / 2)
binarySearch(halfList, item)
}
else {
val halfList = list.drop(1 + (list.length / 2))
binarySearch(halfList, item)
}
}
def binarySearch(numbers : Vector[Int], item : Int) : Option[Int] = {
@tailrec
def search(low : Int, high : Int) : Option[Int] = {
println(s"low = $low ; high = $high")
if (low > high) None
else{
val mid = (low + high)/2
val guess = numbers(mid)
if (guess == item) Some(mid)
else if (guess > item) search(low, mid - 1)
else search(mid + 1, high)
}
}

val myList = List(1,3,5,7,9)
println(binarySearch(myList, 3))
println(binarySearch(myList, -1))
search(0, numbers.length - 1)
}