java - Binary search condition -
i'm confused condition of binary search algorithm , costs me lot of time in programming contests. question when use each of these conditions?
1. while (low < high)
2. while (high - low > 1)
3. while (low <= high)
low
= lowest value in set of solutions.
high
= largest value in set of solutions.
while (low < high)
used when you're searching range[low, high)
. when updatinghigh
, usehigh = mid
. when updatinglow
, uselow = mid + 1
.while (high - low > 1)
used when you're searching range(low, high)
. when updatinghigh
, usehigh = mid
. when updatinglow
, uselow = mid
.while (low <= high)
used when you're searching range[low, high]
. when updatinghigh
, usehigh = mid - 1
. when updatinglow
, uselow = mid + 1
.
code below:
public class binarysearch { public static void main(string[] args) { integer[] nums = { 4, 9, 12, 18, 20, 26, 28, 29, 55 }; (int = 0; < nums.length; ++i) { system.out.println(binarysearch1(nums, nums[i])); system.out.println(binarysearch2(nums, nums[i])); system.out.println(binarysearch3(nums, nums[i])); } } public static <t extends comparable<t>> int binarysearch1(t[] array, t value) { final int not_found = -1; int low = 0; int high = array.length; while (low < high) { int mid = low + (high - low) / 2; int comparison = array[mid].compareto(value); if (comparison == 0) { return mid; } else if (comparison > 0) { high = mid; } else { low = mid + 1; } } return not_found; } public static <t extends comparable<t>> int binarysearch2(t[] array, t value) { final int not_found = -1; int low = -1; int high = array.length; while (high - low > 1) { int mid = low + (high - low) / 2; int comparison = array[mid].compareto(value); if (comparison == 0) { return mid; } else if (comparison > 0) { high = mid; } else { low = mid; } } return not_found; } public static <t extends comparable<t>> int binarysearch3(t[] array, t value) { final int not_found = -1; int low = 0; int high = array.length - 1; while (low <= high) { int mid = low + (high - low) / 2; int comparison = array[mid].compareto(value); if (comparison == 0) { return mid; } else if (comparison > 0) { high = mid - 1; } else { low = mid + 1; } } return not_found; } }
Comments
Post a Comment