Algorithm: Binary Search
miAlism / February 28, 2022
1 min read •
Find a specify element target
int binarySearch(int[] nums, int target) {int left = 0;int right = nums.length - 1; // right js `nums.length - 1`while(left <= right) { // Terminate while loop when left is larger than right.int mid = left + (right - left) / 2;if(nums[mid] == target)return mid;else if (nums[mid] < target)left = mid + 1;else if (nums[mid] > target)right = mid - 1;}return -1;}