Last active
May 3, 2022 14:26
-
-
Save XDo0/6ae4a1abfd237d295b908eb9b07c9d7a to your computer and use it in GitHub Desktop.
Java Search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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