二分查找算法(非递归)

时间:2020-07-09 22:28:57   收藏:0   阅读:64

1.思路分析 对升序数组进行查找,查找具体的值所对应的索引

2.取中间索引跟目标值进行比较,

  如果目标值=中间值,则返回中间值索引

  如果目标值>中间值,则左边索引为中间索引+1

  如果目标值<中间值,则右边索引为中间索引-1

左侧<=右侧索引时进行以上处理,否则就是没有找到返回-1

3.代码实现

package com.hy.tenalgorithm;

/**
* @author hanyong
* @date 2020/7/9 21:21
*/
public class BinarySearchAlgo {
public static void main(String[] args) {
int[] arr = {1, 8, 15, 19, 56, 79};
System.out.print(binarySearchAlgorithm(arr, 79));

}

/**
* @param arr 升序数组
* @param target 要查找的目标
* @return 返回查到的索引
*/
public static int binarySearchAlgorithm(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == target) {
return mid;
} else if (target < arr[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
}
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!