Session 8: Binary Search
Original Session
Date: 16 Nov 2024
Topic: Binary Search
- Concept: In rotated sorted array, Any one half is always sorted.
- Concept: Minimum element in rotated array is always present in unsorted part.
- Concept: In case of duplicates in sorted array, think about moving low and high to exclude duplicates.
Programs
- 33. Search in Rotated Sorted Array
- leetcode here
public int search(int[] nums, int target) { int low = 0; int high = nums.length - 1; while (low <= high) { int mid = (low + high) / 2; if (nums[mid] == target) { return mid; } // If first part is sorted. if (nums[low] <= nums[mid]) { // key lies in this part if (nums[low] <= target && target < nums[mid]) { high = mid - 1; } else { low = mid + 1; } } else { // target is in this part if (nums[mid] < target && target <= nums[high]) { low = mid + 1; } else { high = mid - 1; } } } return -1; }
- leetcode here
- 81. Search in Rotated Sorted Array II
- leetcode here
public boolean search(int[] nums, int target) { int low = 0; int high = nums.length - 1; while (low <= high) { int mid = (low + high) / 2; if (nums[mid] == target) { return true; } if (nums[low] == nums[mid] && nums[high] == nums[mid]) { low ++; high --; }else if (nums[low] <= nums[mid]) { // If first part is sorted. // key lies in this part if (nums[low] <= target && target < nums[mid]) { high = mid - 1; } else { low = mid + 1; } } else { // target is in this part if (nums[mid] < target && target <= nums[high]) { low = mid + 1; } else { high = mid - 1; } } } return false; }
- 153. Find Minimum in Rotated Sorted Array
- leetcode here
public int findMin(int[] nums) { int low = 0; int high = nums.length - 1; while (low < high) { int mid = (low + high) / 2; if (nums[mid] > nums[high]) { low = mid + 1; } else { high = mid; } } return nums[low]; }
- 154. Find Minimum in Rotated Sorted Array II
- leetcode here
public int findMin(int[] nums) { int low = 0; int high = nums.length - 1; while (low < high) { int mid = (low + high) / 2; if (nums[mid] == nums[high]) { high --; }else if (nums[mid] > nums[high]) { low = mid + 1; } else { high = mid; } } return nums[low]; }