Skip to content

Instantly share code, notes, and snippets.

@rgilmutdinov
Created April 2, 2021 12:51
Show Gist options
  • Select an option

  • Save rgilmutdinov/6e06d0bbd310f68d299f60ec0fbbeb64 to your computer and use it in GitHub Desktop.

Select an option

Save rgilmutdinov/6e06d0bbd310f68d299f60ec0fbbeb64 to your computer and use it in GitHub Desktop.
binary search templates
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;
}
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;
}
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

Copy link
Copy Markdown
Author

Template_Diagram

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