Core Concept
Types of problems
Important definitions
Code for ascending binary search
class Solution {
public int search(int[] nums, int target) {
// Time complexity: O(log n), n -> length of input array
// log n because search space is halved at each iteration
// Space complexity: O(1), auxiliary space
int low = 0, high = nums.length - 1;
// Initiate iteration
while(low <= high) {
int mid = low + (high-low)/2; // Get the mid index
// In this case, the nums[mid] == target, so we found the index
if(nums[mid] == target) {
return mid;
}
// If num[mid] is less than the target, we are looking out for a number greater than nums[mid]
// Since the array is sorted in ascending order, search towards the right
else if(nums[mid] < target) {
low = mid + 1;
}
// If target is less than nums[mid], we are looking out for number lesser than nums[mid]
// Subce array is sorted in ascending, search towards left
else if(target > nums[mid]) {
high = mid - 1;
}
}
// If code flow has come here, it means the target is not present in the array
return -1;
}
}Why use `start<=end` and not `start < end`?
Calculating Mid
References:
Last updated