File:Binary Search Depiction.svg

Summary

Description
English: This is an example of a binary search steps through time. Source code and output:
int[] numbersArray = {1,3,4,6,7,8,10,13,14,18,19,21,24,37,40,45,71};
public boolean binarySearchAlgorithm(int targetNumber, int[] numbers)
{
    int lowerLimit = 0;
    int upperLimit = numbers.length - 1;

    while (upperLimit >= lowerLimit)
    {
        int middleNumber = (lowerLimit + upperLimit)/2;

        if (numbers[middleNumber] == targetNumber)
        {
            return true;
        }
        if (numbers[middleNumber] < targetNumber)
        {
            lowerLimit = middleNumber + 1;
        }
        if (numbers[middleNumber] > targetNumber)
        {
            upperLimit = middleNumber - 1;
        }
    }
    return false;
}
System.out.println(binarySearchAlgorithm(7, numbersArray)); //prints "true"

iteration 1

  1. low = 0
  2. high = 16
  3. middle = (0+16)/2 = 16/2 = 8
  4. 7 (target at index 4) < 14 (middle at index 8)
  5. high = middle - 1 = 7

iteration 2

  1. low = 0
  2. high = 7
  3. middle = (0+7)/2 = 7/2 = 3 R 1
  4. 7 (target at index 4) > 6 (middle at index 3)
  5. low = middle + 1 = 4

iteration 3

  1. low = 4
  2. high = 7
  3. middle = (4+7)/2 = 11/2 = 5 R 1
  4. 7 (target at index 4) < 8 (middle at index 5)
  5. high = middle - 1 = 4

iteration 4

  1. low = 4
  2. high = 4
  3. middle = (4+4)/2 = 8/2 = 4
  4. 7 (target at index 4) == 7 (middle at index 4)
Date
Source Own work
Author AlwaysAngry

Licensing

I, the copyright holder of this work, hereby publish it under the following license:
w:en:Creative Commons
attribution share alike
This file is licensed under the Creative Commons Attribution-Share Alike 4.0 International license.
You are free:
  • to share – to copy, distribute and transmit the work
  • to remix – to adapt the work
Under the following conditions:
  • attribution – You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
  • share alike – If you remix, transform, or build upon the material, you must distribute your contributions under the same or compatible license as the original.
Category:CC-BY-SA-4.0#Binary%20Search%20Depiction.svg
Category:Self-published work Category:Binary search algorithm
Category:Binary search algorithm Category:CC-BY-SA-4.0 Category:Pages using deprecated source tags Category:Self-published work