算法-二分查找-非递归
程序员文章站
2022-06-17 19:49:10
...
package datastructure.binarysearch;
import java.util.ArrayList;
public class BinarySearch {
public static void main(String[] args) {
int[] array = {1,3,4,5,6,7,8,23,34,100};
int i = binarySearch3(array, 100);
System.out.println(i);
}
/**
*
* @param arr 升序数组
* @param target 要找的数
* @return 返回这个数的索引,没找到返回-1
*/
public static int binarySearch3(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(arr[mid] < target) {
left = mid + 1;
}else {
right = mid - 1;
}
}
return -1;
}
}
上一篇: Leetcode - 对称二叉树
下一篇: Leetcode - 相同的树