scala实现二分查找

package day04.scala

/**
* Description: 使用二分查找法,查找元素为“70”的索引值 java
*/
object Demo2SecondaySearh {

def main(args: Array[String]) {
30
//使用二分查找法前提:有序集合
val arr = Array(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
var minIndex = 0
var maxIndex = arr.length - 1
var middle = (minIndex + maxIndex) / 2
var index = -1;
while (maxIndex >= minIndex) {
if (arr(middle) == 30) {
index = middle
maxIndex = -1 //为了退出程序,通过让maxIndex小于minIndex
} else if (arr(middle) > 30) {
maxIndex = middle - 1
} else if (arr(middle) < 30) {
minIndex = middle + 1
}
middle = (minIndex + maxIndex) / 2 //没有要查找的元素,最终arr没有被赋值
}
println("index=" + index)


}

}
成就人
原文地址:https://www.cnblogs.com/pingzizhuanshu/p/9157500.html