二分搜索
程序员文章站
2022-07-14 08:02:30
...
以为很麻烦,得调试一下,没想到这也太简单了????
public class BinarySearch {
public int search(int[] nums, int target) {
int i = 0;
int j = nums.length-1;
int mid;
while(i <= j){
mid = (i+j)/2;
if(nums[mid] == target){
return mid;
}
if(nums[mid] < target){
i = mid + 1;
}else {
j = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {
BinarySearch binarySearch = new BinarySearch();
System.out.println(binarySearch.search(new int[]{-1,0,3,5,9,12}, 9));
}
}