Skip to content

Instantly share code, notes, and snippets.

@XDo0
Last active May 3, 2022 14:26
Show Gist options
  • Save XDo0/6ae4a1abfd237d295b908eb9b07c9d7a to your computer and use it in GitHub Desktop.
Save XDo0/6ae4a1abfd237d295b908eb9b07c9d7a to your computer and use it in GitHub Desktop.
Java Search
//binary search on a sorted arrays
public static int binarySearch(int[] nums,int target,int left,int right){
while (left <= right) {
//这里需要注意,计算mid
int mid = left + ((right - left) >> 1);
if (nums[mid] == target) {
return mid;
}else if (nums[mid] < target) {
//这里需要注意,移动左指针
left = mid + 1;
}else if (nums[mid] > target) {
//这里需要注意,移动右指针
right = mid - 1;
}
}
//没有找到该元素,返回 -1
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment