Welcome to BigData School that can get you hired on Small startups or big Product based companies.Are you tired of 30-40 hours of theoritical bigdata courses in the market. Welcome to 240+ hours of Bigdata training. Just subscribe to our popup to get access to our 80+hours of course absolutely free.Try them out and you can join our further course once you are happy with our Demos.

Binary Search Using scala

Big Data    On Thursday 22nd of June 2017 12:10:06 PM By Suraz Ghimire
Here is the program of binary search in scala.
The time complexity is O(logN)
Space complexity O(1)

package sorting.searching

object BinarySearch {

def search(arr: Array[Int], num: Int, start: Int, end: Int): Int = {
println(s"num=$num, start=$start, end=$end")
val midPosition = (start + end) / 2
val midValue = arr(midPosition)

if(end>start) {

if (midValue == num) {
println(s"Number found at position: $midPosition")
return midPosition
else if (num > midValue) { //Its present in 2nd half
println("Search 2nd Half")
search(arr, num, midPosition + 1, end)
else {
println("Search 1st half")
search(arr, num, start, midPosition - 1)
else -1

def main(args: Array[String]): Unit = {
val arr = Array(5, 10, 15, 20, 25, 30)
val num = 2

val position=search(arr, num, 0, arr.length-1)


About Author

Suraz Ghimire