import scala
.collection
.immutable
object binarySearch
{
def
main(args
: Array
[String
]): Unit
= {
val seq
: immutable
.Seq
[Int
] = 1 to
1000
val array
: Array
[Int
] = seq
.toArray
println(binarySearch(array
, 0, array
.length
- 1, array(500)))
}
def
binarySearch(arr
: Array
[Int
], left
: Int
, right
: Int
, findVal
: Int
): Int
= {
if (left
> right
) {
println(left
+ "-" + right
)
return -1
}
if (right
- left
== 1 | right
- left
== 0) {
if (arr(right
) != findVal
&& arr(left
) != findVal
) {
println(arr(right
) + "\t" + findVal
+ "\t" + arr(left
))
return -1
}
}
val midIndex
= (right
- left
) / 2 + left
if (findVal
< arr(midIndex
)) {
binarySearch(arr
, left
, midIndex
- 1, findVal
)
} else if (findVal
> arr(midIndex
)) {
binarySearch(arr
, midIndex
+ 1, right
, findVal
)
}
else {
midIndex
}
}
}
转载请注明原文地址: https://mac.8miu.com/read-497491.html