29 Oct 2009

My take on the binary search in Scala

 

As I’ve learnt in the last few days, programming in a functional based language is a whole different ball game, and its bloody difficult :D. I had trouble finding code relating to doing a binary search in a functional perspective with scala, so I’ve come up with a few lines of code that does so, if anybody has any comments on latering this code to make it more “scala” oriented or “functional” please do so.

def binarySearch(s: String, list: List[RandomString],low: Int, high: Int): Int = {
(high-low) match {

case _ if (high-low) > 0 => { java.lang.Integer.parseInt(s) match {

case _ if java.lang.Integer.parseInt(s) < list(low + (high-low)/2).num => binarySearch(s, list, low, low + (high-low)/2)

case _ if java.lang.Integer.parseInt(s) > list(low + (high-low)/2).num => binarySearch(s, list, (low + (high-low)/2)+1, high)

case _ => (low + (high-low)/2)+1 } }

case _ if (high-low) <= 0 => -1 } }

0 comments:

Post a Comment