Array is most commonly used data structure. You can access an element stored in an array by its index in constant time but searching an element or deleting an element takes O(n) time. We can use binary search to find an element if the array is sorted. Below is the Scala code for binary search in an ordered array. Binary search is very simple, we divide the array in two parts and then decide on which part to search. Search continues recursively until either the element is found or it can't be found.
package com.thescalatutorial.examples object OrderedArrayLookup { def binarySearch(array: Array[Int], value: Int) = { def printArray(array : Array[Int], start : Int, end : Int) { println(array.slice(start, end)mkString(",")) } def binarySearchRecursive(array: Array[Int], start: Int, end: Int, value: Int): Int = { println("start -> " + start + ", end -> " + end) printArray(array, start, end+1) var i = (start + end) / 2 if(start > end) { println("Not Found") return -99999999 } array(i) match { case x if (x == value) => x case x if (x > value) => binarySearchRecursive(array, start, i - 1, value) case x if (x < value) => binarySearchRecursive(array, i + 1, end, value) } } binarySearchRecursive(array, 0, array.size - 1, value) } def main(args: Array[String]) { println("Found -> " + binarySearch(1 until 30 toArray, 11)) } }Running above program will produce following output:
start -> 0, end -> 28
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29
start -> 0, end -> 13
1,2,3,4,5,6,7,8,9,10,11,12,13,14
start -> 7, end -> 13
8,9,10,11,12,13,14
Found -> 11
No comments:
Post a Comment