Adding Scala example for Chapter 2 (#31)

* Add files via upload

* Update 01_countdown.scala

* Update 02_greet.scala

* Update 02_greet.scala

* Create scala

* Delete scala

* Add files via upload

* Add files via upload

* Add files via upload

* Update 01_selection_sort.scala

* Add files via upload
This commit is contained in:
chase-g
2017-10-13 11:37:51 -04:00
committed by Aditya Bhargava
parent 7d6d36ccb2
commit eec9c310ff
2 changed files with 43 additions and 0 deletions

View File

@@ -0,0 +1,18 @@
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)
}
}
val myList = List(1,3,5,7,9)
println(binarySearch(myList, 3))
println(binarySearch(myList, -1))