Search Algorithms
Binary Search
Lets say we want to find a value target
in a data structure.
BinarySearch(data_structure, target):
left ← starting point of the data_structure
right ← end point of the data_structure
while left ≤ right:
mid ← middle element of the data_structure between left and right
if data_structure[mid] == target:
return mid // target found
else if data_structure[mid] < target:
left ← mid + 1 // search in the right half
else:
right ← mid - 1 // search in the left half
return -1 // target not found
public int search(int[] nums, int target) {
int i = 0;
int j = nums.length-1;
int mid = (i+j)/2;
if(i==j) return nums[i]==target ? i: -1;
if(nums[i]==target) return i;
if(nums[j]==target) return j;
while(i<mid && j>mid){
if(nums[mid] == target) return mid;
if(nums[mid]<target) i = mid;
else j = mid;
mid = (i+j)/2;
}
return -1;
}