下面是一个二进制搜索算法,但它没有找到值:
我不认为这个算法是正确的?
'theArray' 被初始化为一个 0 的数组,其中位置 7 的项等于 4。
object various {
//O(log N)
def binarySerachForValue(value : Int) = {
var arraySize = 100
var theArray = new Array[Int](arraySize)
theArray(7) = 4
var timesThrough = 0
var lowIndex = 0
var highIndex = arraySize - 1
while(lowIndex <= highIndex){
var middleIndex = (highIndex + lowIndex) / 2
if(theArray(middleIndex) < value)
lowIndex = middleIndex + 1
else if(theArray(middleIndex) > value)
highIndex = middleIndex - 1
else {
println("Found match in index " + middleIndex)
lowIndex = highIndex + 1
}
timesThrough = timesThrough + 1
}
timesThrough
} //> binarySerachForValue: (value: Int)Int
binarySerachForValue(4) //> res0: Int = 7
}