Algorithms: How to use Binary Search

  1. If the midpoint value is less than the target (what you’re looking for) make your low equal to your midpoint + 1.
  2. If the midpoint value is greater than the target (what your’e looking for) make your high equal to your midpoint — 1.
  3. If the value at the midpoint is what you are looking for, return that.
int[] nodes = new int[5];
nodes[0] = 10;
nodes[1] = 20;
nodes[2] = 30;
nodes[3] = 40;
nodes[4] = 50;

System.out.println(helper(nodes, 0, nodes.length - 1, 20));
low: 0 high: 4 mid: 2 target: 20
low: 0 high: 1 mid: 0 target: 20
low: 1 high: 1 mid: 1 target: 20
value was found at index 1

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store