技术:java8
运行环境:IDEA 15.2 + jdk8 + windows 10
demo功能:java实现一个二分折半查找并测试
public int binarySearch(int[] arr, int x) {
if (arr == null || arr.length == 0) {
return -1;
}
if (x < arr[0]) {
return -1;
}
if (x > arr[arr.length - 1]) {
return -1;
}
int returnIndex = -1;
int startIndex = 0;
int endIndex = arr.length - 1;
int middleIndex = (startIndex + endIndex) / 2;
while (true) {
if (x == arr[startIndex]) {
returnIndex = startIndex;
break;
}
if (x == arr[endIndex]) {
returnIndex = endIndex;
break;
}
if (x == arr[middleIndex]) {
returnIndex = middleIndex;
break;
}
if (middleIndex == startIndex || middleIndex == endIndex) {
break;
}
if (x > arr[middleIndex]) {
startIndex = middleIndex;
}
if (x < arr[middleIndex]) {
endIndex = middleIndex;
}
middleIndex = (startIndex + endIndex) / 2;
}
return returnIndex;
}
源代码中包含测试用例, 目前都是测试通过的
欢迎添加微信,互相学习↑↑↑ -_-
白老虎
programming is not only to solve problems, ways to think
grafana 级连 菜单 templating (variables) 配置
rocketmq 集群搭建 (2master + 2slave + 2namesrv)
AI 机器人 抓取 微信 聊天中的 百度网盘 分享地址和密码