Created
April 2, 2021 12:51
-
-
Save rgilmutdinov/6e06d0bbd310f68d299f60ec0fbbeb64 to your computer and use it in GitHub Desktop.
binary search templates
This file contains hidden or 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
| public int BinarySearch1(int[] nums, int target){ | |
| if (nums == null || nums.Length == 0) { | |
| return -1; | |
| } | |
| int lo = 0, hi = nums.Length - 1; | |
| while (lo <= hi) { | |
| // Prevent (lo + hi) overflow | |
| int mid = lo + (hi - lo) / 2; | |
| if (nums[mid] == target) { | |
| return mid; | |
| } else if (nums[mid] < target) { | |
| lo = mid + 1; | |
| } else { | |
| hi = mid - 1; | |
| } | |
| } | |
| // End Condition: left > hi | |
| return -1; | |
| } |
This file contains hidden or 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
| public int BinarySearch2(int[] nums, int target) { | |
| if (nums == null || nums.Length == 0) { | |
| return -1; | |
| } | |
| int lo = 0, hi = nums.Length; | |
| while (lo < hi) { | |
| // Prevent (lo + hi) overflow | |
| int mid = lo + (hi - lo) / 2; | |
| if (nums[mid] == target) { | |
| return mid; | |
| } else if(nums[mid] < target) { | |
| lo = mid + 1; | |
| } else { | |
| hi = mid; | |
| } | |
| } | |
| // Post-processing: | |
| // End Condition: lo == hi | |
| if (lo != nums.Length && nums[lo] == target) { | |
| return lo; | |
| } | |
| return -1; | |
| } |
This file contains hidden or 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
| public int BinarySearch3(int[] nums, int target) { | |
| if (nums == null || nums.Length == 0) { | |
| return -1; | |
| } | |
| int lo = 0, hi = nums.Length - 1; | |
| while (lo + 1 < hi) { | |
| // Prevent (lo + hi) overflow | |
| int mid = lo + (hi - lo) / 2; | |
| if (nums[mid] == target) { | |
| return mid; | |
| } else if (nums[mid] < target) { | |
| lo = mid; | |
| } else { | |
| hi = mid; | |
| } | |
| } | |
| // Post-processing: | |
| // End Condition: lo + 1 == hi | |
| if (nums[lo] == target) return lo; | |
| if (nums[hi] == target) return hi; | |
| return -1; | |
| } |
rgilmutdinov
commented
Apr 4, 2021
Author

Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment