When looking up a word in a dictionary or finding a contact in an alphabetically sorted phone book, you can jump to the middle and decide which half to search next. Binary search formalizes that idea for sorted arrays.

Basic Implementation

Basic.java
Replay: real traced execution (multi-file project)
public class Basic {
    static int binarySearch(int[] arr, int target) {
        int low = 0;
        int high = arr.length - 1;
        while (low <= high) {
            int mid = (low + high) / 2;

            if (arr[mid] == target) {
                return mid;  // found
            } else if (arr[mid] < target) {
                low = mid + 1;  // search right half
            } else {
                high = mid - 1;  // search left half
            }
        }

        return -1;  // not found
    }

    public static void main(String[] args) {
        int[] sorted = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};

        System.out.println("Array: " + java.util.Arrays.toString(sorted));
        System.out.println("Search 7: index " + binarySearch(sorted, 7));
        System.out.println("Search 1: index " + binarySearch(sorted, 1));
        System.out.println("Search 19: index " + binarySearch(sorted, 19));
        System.out.println("Search 10: index " + binarySearch(sorted, 10));
    }
}
  1. public static void main(String[] args)

    20public static void main(String[] args) {21    int[] sorted = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};2223    System.out.println("Array: " + java.util.Arrays.toString(sorted));24    System.out.println("Search 7: index " + binarySearch(sorted, 7));25    System.out.println("Search 1: index " + binarySearch(sorted, 1));
    outputArray: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
  2. low ← 0, high ← 9

    pass 1 of 4
    1public class Basic {2    static int binarySearch(int[] arr, int target7) {3        int low→ 0 = 0;4        int high→ 9 = arr.length10 - 1;5        while (low <= high) {
    All 4 passes — pass 1 is the card above
    passtargetlowhigh
    1709
    2109
    31909
    41009
  3. mid ← 4

    pass 1 of 14
    4int high = arr.length - 1;5while (low0 <= high9) {6    int mid→ 4 = (low0 + high9) / 2;
    14 passes — pass 1 is the card above
    passlowhighmid
    1094
    2031
    3232
    4333
    5094
    6031
    7000
    8094
    9597
    ⋯ 3 more passes ⋯
    13597
    14565
  4. high ← 3

    pass 1 of 5
    11    low = mid + 1;  // search right half12} else {13    high→ 3 = mid4 - 1;  // search left half14}
    All 5 passes — pass 1 is the card above
    passmidhigh
    143
    243
    310
    476
    554
  5. low ← 2

    pass 1 of 6
    9    return mid;  // found10} else if (arr[mid]3 < target7) {11    low→ 2 = mid1 + 1;  // search right half12} else {
    All 6 passes — pass 1 is the card above
    passarr[mid]midtargetlow
    13172
    25273
    394195
    4157198
    5178199
    694105
  6. if (arr[mid] == target)

    pass 1 of 3
    8if (arr[mid]7 == target7) {9    return mid3;  // found10} else if (arr[mid] < target) {
    All 3 passes — pass 1 is the card above
    passarr[mid]midtarget
    1737
    2101
    319919
  7. System.out.println("Search 7: index " + binarySearch(sorted, 7));

    23System.out.println("Array: " + java.util.Arrays.toString(sorted));24System.out.println("Search 7: index " + binarySearch(sorted, 7));25System.out.println("Search 1: index " + binarySearch(sorted, 1));26System.out.println("Search 19: index " + binarySearch(sorted, 19));
    outputSearch 7: index 3
  8. System.out.println("Search 1: index " + binarySearch(sorted, 1));

    24System.out.println("Search 7: index " + binarySearch(sorted, 7));25System.out.println("Search 1: index " + binarySearch(sorted, 1));26System.out.println("Search 19: index " + binarySearch(sorted, 19));27System.out.println("Search 10: index " + binarySearch(sorted, 10));
    outputSearch 1: index 0
  9. System.out.println("Search 19: index " + binarySearch(sorted, 19));

    25    System.out.println("Search 1: index " + binarySearch(sorted, 1));26    System.out.println("Search 19: index " + binarySearch(sorted, 19));27    System.out.println("Search 10: index " + binarySearch(sorted, 10));28}
    outputSearch 19: index 9
  10. return -1; // not found

    17    return -1;  // not found18}
  11. System.out.println("Search 10: index " + binarySearch(sorted, 10));

    26    System.out.println("Search 19: index " + binarySearch(sorted, 19));27    System.out.println("Search 10: index " + binarySearch(sorted, 10));28}
    outputSearch 10: index -1
Binary Search A divide-and-conquer search algorithm that halves the search space with each comparison. It requires sorted data and runs in O(log n) time.

Tracing the Algorithm

The low, mid, and high boundaries show how each comparison removes half of the remaining search area.

target
Trace.java
Replay: real traced execution (multi-file project)
public class Trace {
    static int binarySearchTrace(int[] arr, int target) {
        int low = 0;
        int high = arr.length - 1;
        int iteration = 0;
        while (low <= high) {
            iteration++;
            int mid = (low + high) / 2;

            System.out.printf("Iter %d: low=%d, mid=%d, high=%d, arr[mid]=%d%n",
                            iteration, low, mid, high, arr[mid]);

            if (arr[mid] == target) {
                System.out.println("Found at index " + mid);
                return mid;
            } else if (arr[mid] < target) {
                System.out.println("  Target > mid, search right");
                low = mid + 1;
            } else {
                System.out.println("  Target < mid, search left");
                high = mid - 1;
            }
        }

        System.out.println("Not found");
        return -1;
    }

    public static void main(String[] args) {
        int[] sorted = {10, 20, 30, 40, 50, 60, 70, 80, 90};
        int target = 70;

        System.out.println("Searching for " + target + ":");
        binarySearchTrace(sorted, target);
    }
}
public class Trace {
    static int binarySearchTrace(int[] arr, int target) {
        int low = 0;
        int high = arr.length - 1;
        int iteration = 0;
        while (low <= high) {
            iteration++;
            int mid = (low + high) / 2;

            System.out.printf("Iter %d: low=%d, mid=%d, high=%d, arr[mid]=%d%n",
                            iteration, low, mid, high, arr[mid]);

            if (arr[mid] == target) {
                System.out.println("Found at index " + mid);
                return mid;
            } else if (arr[mid] < target) {
                System.out.println("  Target > mid, search right");
                low = mid + 1;
            } else {
                System.out.println("  Target < mid, search left");
                high = mid - 1;
            }
        }

        System.out.println("Not found");
        return -1;
    }

    public static void main(String[] args) {
        int[] sorted = {10, 20, 30, 40, 50, 60, 70, 80, 90};
        int target = 10;

        System.out.println("Searching for " + target + ":");
        binarySearchTrace(sorted, target);
    }
}
public class Trace {
    static int binarySearchTrace(int[] arr, int target) {
        int low = 0;
        int high = arr.length - 1;
        int iteration = 0;
        while (low <= high) {
            iteration++;
            int mid = (low + high) / 2;

            System.out.printf("Iter %d: low=%d, mid=%d, high=%d, arr[mid]=%d%n",
                            iteration, low, mid, high, arr[mid]);

            if (arr[mid] == target) {
                System.out.println("Found at index " + mid);
                return mid;
            } else if (arr[mid] < target) {
                System.out.println("  Target > mid, search right");
                low = mid + 1;
            } else {
                System.out.println("  Target < mid, search left");
                high = mid - 1;
            }
        }

        System.out.println("Not found");
        return -1;
    }

    public static void main(String[] args) {
        int[] sorted = {10, 20, 30, 40, 50, 60, 70, 80, 90};
        int target = 25;

        System.out.println("Searching for " + target + ":");
        binarySearchTrace(sorted, target);
    }
}
  1. target ← 70

    29public static void main(String[] args) {30    int[] sorted = {10, 20, 30, 40, 50, 60, 70, 80, 90};31    int target→ 70 = 70; //@target=70, 25, 103233    System.out.println("Searching for " + target70 + ":");34    binarySearchTrace(sorted, target70);35}
    outputSearching for 70:
  2. low ← 0, high ← 8, iteration ← 0

    1public class Trace {2    static int binarySearchTrace(int[] arr, int target70) {3        int low→ 0 = 0;4        int high→ 8 = arr.length9 - 1;5        int iteration→ 0 = 0;6        while (low <= high) {
  3. iteration ← 1, mid ← 4

    pass 1 of 2
    5int iteration = 0;6while (low0 <= high8) {7    iteration→ 1++;8    int mid→ 4 = (low0 + high8) / 2;910    System.out.printf("Iter %d: low=%d, mid=%d, high=%d, arr[mid]=%d%n",11                    iteration1, low0, mid4, high8, arr[mid]50);
  4. low ← 5

    15    return mid;16} else if (arr[mid]50 < target70) {17    System.out.println("  Target > mid, search right");18    low→ 5 = mid4 + 1;19} else {
    output  Target > mid, search right
  5. iteration ← 2, mid ← 6

    pass 2 of 2
    5int iteration = 0;6while (low5 <= high8) {7    iteration→ 2++;8    int mid→ 6 = (low5 + high8) / 2;910    System.out.printf("Iter %d: low=%d, mid=%d, high=%d, arr[mid]=%d%n",11                    iteration2, low5, mid6, high8, arr[mid]70);
  6. if (arr[mid] == target)

    13if (arr[mid]70 == target70) {14    System.out.println("Found at index " + mid6);15    return mid6;16} else if (arr[mid] < target) {
    outputFound at index 6
  7. binarySearchTrace(sorted, target);

    33    System.out.println("Searching for " + target + ":");34    binarySearchTrace(sorted, target70);35}
  1. target ← 10

    29public static void main(String[] args) {30    int[] sorted = {10, 20, 30, 40, 50, 60, 70, 80, 90};31    int target→ 10 = 10;3233    System.out.println("Searching for " + target10 + ":");34    binarySearchTrace(sorted, target10);35}
    outputSearching for 10:
  2. low ← 0, high ← 8, iteration ← 0

    1public class Trace {2    static int binarySearchTrace(int[] arr, int target10) {3        int low→ 0 = 0;4        int high→ 8 = arr.length9 - 1;5        int iteration→ 0 = 0;6        while (low <= high) {
  3. iteration ← 1, mid ← 4

    pass 1 of 3
    5int iteration = 0;6while (low0 <= high8) {7    iteration→ 1++;8    int mid→ 4 = (low0 + high8) / 2;910    System.out.printf("Iter %d: low=%d, mid=%d, high=%d, arr[mid]=%d%n",11                    iteration1, low0, mid4, high8, arr[mid]50);
    All 3 passes — pass 1 is the card above
    passarr[mid]targetiterationmidhigh
    1500 143
    2201 210
    310102 300
  4. high ← 3

    pass 1 of 2
    18    low = mid + 1;19} else {20    System.out.println("  Target < mid, search left");21    high→ 3 = mid4 - 1;22}
    output  Target < mid, search left
  5. high ← 0

    pass 2 of 2
    18    low = mid + 1;19} else {20    System.out.println("  Target < mid, search left");21    high→ 0 = mid1 - 1;22}
    output  Target < mid, search left
  6. if (arr[mid] == target)

    13if (arr[mid]10 == target10) {14    System.out.println("Found at index " + mid0);15    return mid0;16} else if (arr[mid] < target) {
    outputFound at index 0
  7. binarySearchTrace(sorted, target);

    33    System.out.println("Searching for " + target + ":");34    binarySearchTrace(sorted, target10);35}
  1. target ← 25

    29public static void main(String[] args) {30    int[] sorted = {10, 20, 30, 40, 50, 60, 70, 80, 90};31    int target→ 25 = 25;3233    System.out.println("Searching for " + target25 + ":");34    binarySearchTrace(sorted, target25);35}
    outputSearching for 25:
  2. low ← 0, high ← 8, iteration ← 0

    1public class Trace {2    static int binarySearchTrace(int[] arr, int target25) {3        int low→ 0 = 0;4        int high→ 8 = arr.length9 - 1;5        int iteration→ 0 = 0;6        while (low <= high) {
  3. iteration ← 1, mid ← 4

    pass 1 of 3
    5int iteration = 0;6while (low0 <= high8) {7    iteration→ 1++;8    int mid→ 4 = (low0 + high8) / 2;910    System.out.printf("Iter %d: low=%d, mid=%d, high=%d, arr[mid]=%d%n",11                    iteration1, low0, mid4, high8, arr[mid]50);
    All 3 passes — pass 1 is the card above
    passarr[mid]targetiterationmidhighlow
    1500 1430
    220251 2132
    3302 3212
  4. high ← 3

    pass 1 of 2
    18    low = mid + 1;19} else {20    System.out.println("  Target < mid, search left");21    high→ 3 = mid4 - 1;22}
    output  Target < mid, search left
  5. low ← 2

    15    return mid;16} else if (arr[mid]20 < target25) {17    System.out.println("  Target > mid, search right");18    low→ 2 = mid1 + 1;19} else {
    output  Target > mid, search right
  6. high ← 1

    pass 2 of 2
    18    low = mid + 1;19} else {20    System.out.println("  Target < mid, search left");21    high→ 1 = mid2 - 1;22}
    output  Target < mid, search left
  7. System.out.println("Not found");

    25    System.out.println("Not found");26    return -1;27}
    outputNot found
  8. binarySearchTrace(sorted, target);

    33    System.out.println("Searching for " + target + ":");34    binarySearchTrace(sorted, target25);35}

Recursive Version

Binary search can also be expressed recursively by searching either the left half or the right half.

Recursive.java
Replay: real traced execution (multi-file project)
public class Recursive {
    static int binarySearchRecursive(int[] arr, int target, int low, int high) {
        if (low > high) {
            return -1;  // not found
        }
        int mid = (low + high) / 2;

        if (arr[mid] == target) {
            return mid;  // found
        } else if (arr[mid] < target) {
            return binarySearchRecursive(arr, target, mid + 1, high);  // right
        } else {
            return binarySearchRecursive(arr, target, low, mid - 1);  // left
        }
    }

    static int binarySearch(int[] arr, int target) {
        return binarySearchRecursive(arr, target, 0, arr.length - 1);
    }

    public static void main(String[] args) {
        int[] sorted = {2, 5, 8, 12, 16, 23, 38, 45, 56, 67, 78};

        System.out.println("Array: " + java.util.Arrays.toString(sorted));
        System.out.println("Search 23: index " + binarySearch(sorted, 23));
        System.out.println("Search 2: index " + binarySearch(sorted, 2));
        System.out.println("Search 100: index " + binarySearch(sorted, 100));
    }
}
  1. public static void main(String[] args)

    21public static void main(String[] args) {22    int[] sorted = {2, 5, 8, 12, 16, 23, 38, 45, 56, 67, 78};2324    System.out.println("Array: " + java.util.Arrays.toString(sorted));25    System.out.println("Search 23: index " + binarySearch(sorted, 23));26    System.out.println("Search 2: index " + binarySearch(sorted, 2));
    outputArray: [2, 5, 8, 12, 16, 23, 38, 45, 56, 67, 78]
  2. static int binarySearch(int[] arr, int target)

    pass 1 of 3
    17static int binarySearch(int[] arr, int target23) {18    return binarySearchRecursive(arr, target23, 0, arr.length11 - 1);19}
    All 3 passes — pass 1 is the card above
    passtargetarr[mid]midlowhigh
    123235
    22250
    31001110
  3. mid ← 5

    pass 1 of 9
    1public class Recursive {2    static int binarySearchRecursive(int[] arr, int target23, int low0, int high10) {3        if (low > high) {4            return -1;  // not found5        }6        int mid→ 5 = (low0 + high10) / 2;
    All 9 passes — pass 1 is the card above
    passtargetlowhigharr[mid]mid
    123010235
    220105
    32042
    420120
    51000105
    61006108
    71009109
    8100101010
    91001110
  4. if (arr[mid] == target)

    pass 1 of 2
    8if (arr[mid]23 == target23) {9    return mid5;  // found10} else if (arr[mid] < target) {
  5. System.out.println("Search 23: index " + binarySearch(sorted, 23));

    24System.out.println("Array: " + java.util.Arrays.toString(sorted));25System.out.println("Search 23: index " + binarySearch(sorted, 23));26System.out.println("Search 2: index " + binarySearch(sorted, 2));27System.out.println("Search 100: index " + binarySearch(sorted, 100));
    outputSearch 23: index 5
  6. else

    pass 1 of 2
    11    return binarySearchRecursive(arr, target, mid + 1, high);  // right12} else {13    return binarySearchRecursive(arr, target2, low0, mid5 - 1);  // left14}
  7. else

    pass 2 of 2
    11    return binarySearchRecursive(arr, target, mid + 1, high);  // right12} else {13    return binarySearchRecursive(arr, target2, low0, mid2 - 1);  // left14}
  8. if (arr[mid] == target)

    pass 2 of 2
    8if (arr[mid]2 == target2) {9    return mid0;  // found10} else if (arr[mid] < target) {
  9. System.out.println("Search 2: index " + binarySearch(sorted, 2));

    25    System.out.println("Search 23: index " + binarySearch(sorted, 23));26    System.out.println("Search 2: index " + binarySearch(sorted, 2));27    System.out.println("Search 100: index " + binarySearch(sorted, 100));28}
    outputSearch 2: index 0
  10. if (arr[mid] < target)

    pass 1 of 4
    9    return mid;  // found10} else if (arr[mid]23 < target100) {11    return binarySearchRecursive(arr, target100, mid5 + 1, high10);  // right12} else {
    All 4 passes — pass 1 is the card above
    passarr[mid]midlow
    1235
    2568
    3679
    4781011
  11. if (low > high)

    2static int binarySearchRecursive(int[] arr, int target, int low, int high) {3    if (low11 > high10) {4        return -1;  // not found5    }
  12. System.out.println("Search 100: index " + binarySearch(sorted, 100));

    26    System.out.println("Search 2: index " + binarySearch(sorted, 2));27    System.out.println("Search 100: index " + binarySearch(sorted, 100));28}
    outputSearch 100: index -1

Finding Insertion Points

InsertionPoint.java
Replay: real traced execution (multi-file project)
public class InsertionPoint {
    static int findInsertionPoint(int[] arr, int value) {
        int low = 0;
        int high = arr.length - 1;
        while (low <= high) {
            int mid = (low + high) / 2;

            if (arr[mid] < value) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }

        return low;  // insertion point
    }

    public static void main(String[] args) {
        int[] sorted = {10, 20, 30, 40, 50, 60, 70};

        System.out.println("Array: " + java.util.Arrays.toString(sorted));
        System.out.println("Insert 25 at index: " + findInsertionPoint(sorted, 25));
        System.out.println("Insert 5 at index: " + findInsertionPoint(sorted, 5));
        System.out.println("Insert 75 at index: " + findInsertionPoint(sorted, 75));
        System.out.println("Insert 40 at index: " + findInsertionPoint(sorted, 40));
    }
}
  1. public static void main(String[] args)

    18public static void main(String[] args) {19    int[] sorted = {10, 20, 30, 40, 50, 60, 70};2021    System.out.println("Array: " + java.util.Arrays.toString(sorted));22    System.out.println("Insert 25 at index: " + findInsertionPoint(sorted, 25));23    System.out.println("Insert 5 at index: " + findInsertionPoint(sorted, 5));
    outputArray: [10, 20, 30, 40, 50, 60, 70]
  2. low ← 0, high ← 6

    pass 1 of 4
    1public class InsertionPoint {2    static int findInsertionPoint(int[] arr, int value25) {3        int low→ 0 = 0;4        int high→ 6 = arr.length7 - 1;5        while (low <= high) {
    All 4 passes — pass 1 is the card above
    passvaluelowhigh
    12506
    2506
    37506
    44006
  3. mid ← 3

    pass 1 of 12
    4int high = arr.length - 1;5while (low0 <= high6) {6    int mid→ 3 = (low0 + high6) / 2;
    All 12 passes — pass 1 is the card above
    passlowhighmid
    1063
    2021
    3222
    4063
    5021
    6000
    7063
    8465
    9666
    10063
    11021
    12222
  4. high ← 2

    pass 1 of 6
    9    low = mid + 1;10} else {11    high→ 2 = mid3 - 1;12}
    All 6 passes — pass 1 is the card above
    passmidhigh
    132
    221
    332
    410
    50-1
    632
  5. low ← 2

    pass 1 of 6
    8if (arr[mid]20 < value25) {9    low→ 2 = mid1 + 1;10} else {
    All 6 passes — pass 1 is the card above
    passarr[mid]midvaluelow
    1201252
    2403754
    3605756
    4706757
    5201402
    6302403
  6. return low; // insertion point

    15    return low2;  // insertion point16}
  7. System.out.println("Insert 25 at index: " + findInsertionPoint(sorted,…

    21System.out.println("Array: " + java.util.Arrays.toString(sorted));22System.out.println("Insert 25 at index: " + findInsertionPoint(sorted, 25));23System.out.println("Insert 5 at index: " + findInsertionPoint(sorted, 5));24System.out.println("Insert 75 at index: " + findInsertionPoint(sorted, 75));
    outputInsert 25 at index: 2
  8. return low; // insertion point

    15    return low0;  // insertion point16}
  9. System.out.println("Insert 5 at index: " + findInsertionPoint(sorted, …

    22System.out.println("Insert 25 at index: " + findInsertionPoint(sorted, 25));23System.out.println("Insert 5 at index: " + findInsertionPoint(sorted, 5));24System.out.println("Insert 75 at index: " + findInsertionPoint(sorted, 75));25System.out.println("Insert 40 at index: " + findInsertionPoint(sorted, 40));
    outputInsert 5 at index: 0
  10. return low; // insertion point

    15    return low7;  // insertion point16}
  11. System.out.println("Insert 75 at index: " + findInsertionPoint(sorted,…

    23    System.out.println("Insert 5 at index: " + findInsertionPoint(sorted, 5));24    System.out.println("Insert 75 at index: " + findInsertionPoint(sorted, 75));25    System.out.println("Insert 40 at index: " + findInsertionPoint(sorted, 40));26}
    outputInsert 75 at index: 7
  12. return low; // insertion point

    15    return low3;  // insertion point16}
  13. System.out.println("Insert 40 at index: " + findInsertionPoint(sorted,…

    24    System.out.println("Insert 75 at index: " + findInsertionPoint(sorted, 75));25    System.out.println("Insert 40 at index: " + findInsertionPoint(sorted, 40));26}
    outputInsert 40 at index: 3
Insertion Point When a target is not found, binary search can return where the value belongs to keep the data sorted.

Comparison with Linear Search

Binary search pays off when data is already sorted and searched repeatedly.

Comparison.java
Replay: real traced execution (multi-file project)
public class Comparison {
    static int linearSearch(int[] arr, int target) {
        int comparisons = 0;
        for (int i = 0; i < arr.length; i++) {
            comparisons++;
            if (arr[i] == target) {
                System.out.println("  Linear: " + comparisons + " comparisons");
                return i;
            }
        }
        System.out.println("  Linear: " + comparisons + " comparisons (not found)");
        return -1;
    }

    static int binarySearch(int[] arr, int target) {
        int low = 0, high = arr.length - 1;
        int comparisons = 0;

        while (low <= high) {
            comparisons++;
            int mid = (low + high) / 2;

            if (arr[mid] == target) {
                System.out.println("  Binary: " + comparisons + " comparisons");
                return mid;
            } else if (arr[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        System.out.println("  Binary: " + comparisons + " comparisons (not found)");
        return -1;
    }

    public static void main(String[] args) {
        int[] sorted = new int[32];
        for (int i = 0; i < sorted.length; i++) {
            sorted[i] = i * 2;  // even numbers 0, 2, 4, ..., 62
        }

        System.out.println("Array size: " + sorted.length);
        System.out.println("\nSearch for 30:");
        linearSearch(sorted, 30);
        binarySearch(sorted, 30);

        System.out.println("\nSearch for 63 (not found):");
        linearSearch(sorted, 63);
        binarySearch(sorted, 63);
    }
}
  1. public static void main(String[] args)

    36public static void main(String[] args) {37    int[] sorted = new int[32];38    for (int i = 0; i < sorted.length; i++) {
  2. for (int i = 0; i < sorted.length; i++)

    pass 1 of 32
    37int[] sorted = new int[32];38for (int i0 = 0; i < sorted.length32; i++) {39    sorted[i]0 = i0 * 2;  // even numbers 0, 2, 4, ..., 6240}
    32 passes — pass 1 is the card above
    passisorted[i]
    100
    210 2
    320 4
    430 6
    540 8
    650 10
    760 12
    870 14
    980 16
    ⋯ 21 more passes ⋯
    31300 60
    32310 62
  3. System.out.println("Array size: " + sorted.length);

    42System.out.println("Array size: " + sorted.length32);43System.out.println("\nSearch for 30:");44linearSearch(sorted, 30);45binarySearch(sorted, 30);
    outputArray size: 32
    
    Search for 30:
  4. comparisons ← 0

    pass 1 of 2
    1public class Comparison {2    static int linearSearch(int[] arr, int target30) {3        int comparisons→ 0 = 0;4        for (int i = 0; i < arr.length; i++) {
  5. comparisons ← 1

    pass 1 of 48
    3int comparisons = 0;4for (int i0 = 0; i < arr.length32; i++) {5    comparisons→ 1++;6    if (arr[i] == target) {
    48 passes — pass 1 is the card above
    passiarr[i]targetcomparisons
    100 1
    211 2
    322 3
    433 4
    544 5
    655 6
    766 7
    877 8
    988 9
    ⋯ 37 more passes ⋯
    473030 31
    483131 32
  6. if (arr[i] == target)

    5comparisons++;6if (arr[i]30 == target30) {7    System.out.println("  Linear: " + comparisons16 + " comparisons");8    return i15;9}
    output  Linear: 16 comparisons
  7. linearSearch(sorted, 30);

    43System.out.println("\nSearch for 30:");44linearSearch(sorted, 30);45binarySearch(sorted, 30);
  8. high ← 31, comparisons ← 0

    pass 1 of 2
    15static int binarySearch(int[] arr, int target30) {16    int low = 0, high→ 31 = arr.length32 - 1;17    int comparisons→ 0 = 0;
  9. comparisons ← 1, mid ← 15

    pass 1 of 7
    19while (low0 <= high31) {20    comparisons→ 1++;21    int mid→ 15 = (low0 + high31) / 2;
    All 7 passes — pass 1 is the card above
    passlowarr[mid]targetcomparisonsmid
    1030300 115
    200 115
    3161 223
    4242 327
    5283 429
    6304 530
    7315 631
  10. if (arr[mid] == target)

    23if (arr[mid]30 == target30) {24    System.out.println("  Binary: " + comparisons1 + " comparisons");25    return mid15;26} else if (arr[mid] < target) {
    output  Binary: 1 comparisons
  11. binarySearch(sorted, 30);

    44linearSearch(sorted, 30);45binarySearch(sorted, 30);4647System.out.println("\nSearch for 63 (not found):");48linearSearch(sorted, 63);49binarySearch(sorted, 63);
    output
    Search for 63 (not found):
  12. comparisons ← 0

    pass 2 of 2
    1public class Comparison {2    static int linearSearch(int[] arr, int target63) {3        int comparisons→ 0 = 0;4        for (int i = 0; i < arr.length; i++) {
  13. System.out.println(" Linear: " + comparisons + " comparisons (not fou…

    10    }11    System.out.println("  Linear: " + comparisons32 + " comparisons (not found)");12    return -1;13}
    output  Linear: 32 comparisons (not found)
  14. linearSearch(sorted, 63);

    47    System.out.println("\nSearch for 63 (not found):");48    linearSearch(sorted, 63);49    binarySearch(sorted, 63);50}
  15. high ← 31, comparisons ← 0

    pass 2 of 2
    15static int binarySearch(int[] arr, int target63) {16    int low = 0, high→ 31 = arr.length32 - 1;17    int comparisons→ 0 = 0;
  16. low ← 16

    pass 1 of 6
    25    return mid;26} else if (arr[mid]30 < target63) {27    low→ 16 = mid15 + 1;28} else {
    All 6 passes — pass 1 is the card above
    passarr[mid]midlow
    1301516
    2462324
    3542728
    4582930
    5603031
    6623132
  17. System.out.println(" Binary: " + comparisons + " comparisons (not fou…

    31    }32    System.out.println("  Binary: " + comparisons6 + " comparisons (not found)");33    return -1;34}
    output  Binary: 6 comparisons (not found)
  18. binarySearch(sorted, 63);

    48    linearSearch(sorted, 63);49    binarySearch(sorted, 63);50}

Practical Use

Sorted phone books, dictionaries, indexes, and ordered tables use this same search shape.

Practical.java
Replay: real traced execution (multi-file project)
public class Practical {
    record Contact(String name, String phone) implements Comparable<Contact> {
        @Override
        public int compareTo(Contact other) {
            return this.name.compareTo(other.name);
        }
    }

    static int searchByName(Contact[] contacts, String name) {
        int low = 0;
        int high = contacts.length - 1;
        while (low <= high) {
            int mid = (low + high) / 2;
            int cmp = contacts[mid].name().compareTo(name);

            if (cmp == 0) {
                return mid;  // found
            } else if (cmp < 0) {
                low = mid + 1;  // search right
            } else {
                high = mid - 1;  // search left
            }
        }

        return -1;  // not found
    }

    public static void main(String[] args) {
        Contact[] phonebook = {
            new Contact("Alice", "555-1001"),
            new Contact("Bob", "555-1002"),
            new Contact("Charlie", "555-1003"),
            new Contact("Diana", "555-1004"),
            new Contact("Eve", "555-1005"),
            new Contact("Frank", "555-1006"),
            new Contact("Grace", "555-1007"),
            new Contact("Henry", "555-1008")
        };

        System.out.println("Phone book (" + phonebook.length + " contacts):\n");

        String[] searches = {"Charlie", "Grace", "Alice", "Zoe"};
        for (String name : searches) {
            int index = searchByName(phonebook, name);
            if (index >= 0) {
                Contact c = phonebook[index];
                System.out.println(name + ": " + c.phone());
            } else {
                System.out.println(name + ": not found");
            }
        }
    }
}
  1. public static void main(String[] args)

    28public static void main(String[] args) {29    Contact[] phonebook = {30        new Contact("Alice", "555-1001"),31        new Contact("Bob", "555-1002"),32        new Contact("Charlie", "555-1003"),33        new Contact("Diana", "555-1004"),34        new Contact("Eve", "555-1005"),35        new Contact("Frank", "555-1006"),36        new Contact("Grace", "555-1007"),37        new Contact("Henry", "555-1008")38    };3940    System.out.println("Phone book (" + phonebook.length8 + " contacts):\n");4142    String[] searches = {"Charlie", "Grace", "Alice", "Zoe"};43    for (String name : searches) {
    outputPhone book (8 contacts):
  2. for (String name : searches)

    pass 1 of 4
    42String[] searches = {"Charlie", "Grace", "Alice", "Zoe"};43for (String nameCharlie : searches) {44    int index = searchByName(phonebook, nameCharlie);45    if (index >= 0) {
    All 4 passes — pass 1 is the card above
    passname
    1Charlie
    2Grace
    3Alice
    4Zoe
  3. low ← 0, high ← 7

    pass 1 of 4
    9static int searchByName(Contact[] contacts, String nameCharlie) {10    int low→ 0 = 0;11    int high→ 7 = contacts.length8 - 1;12    while (low <= high) {
    All 4 passes — pass 1 is the card above
    passnamelowhigh
    1Charlie07
    2Grace07
    3Alice07
    4Zoe07
  4. mid ← 3, cmp ← 1

    pass 1 of 13
    11int high = contacts.length - 1;12while (low0 <= high7) {13    int mid→ 3 = (low0 + high7) / 2;14    int cmp→ 1 = contacts[mid]Contact[name=Diana, phone=555-1004].name().compareTo(nameCharlie);
    13 passes — pass 1 is the card above
    passlowhighcontacts[mid]namemidcmp
    107Contact[name=Diana, phone=555-1004]Charlie31
    202Contact[name=Bob, phone=555-1002]Charlie1-1
    322Contact[name=Charlie, phone=555-1003]Charlie20
    407Contact[name=Diana, phone=555-1004]Grace3-3
    547Contact[name=Frank, phone=555-1006]Grace5-1
    667Contact[name=Grace, phone=555-1007]Grace60
    707Contact[name=Diana, phone=555-1004]Alice33
    802Contact[name=Bob, phone=555-1002]Alice11
    900Contact[name=Alice, phone=555-1001]Alice00
    ⋯ 2 more passes ⋯
    1267Contact[name=Grace, phone=555-1007]Zoe6-19
    1377Contact[name=Henry, phone=555-1008]Zoe7-18
  5. high ← 2

    pass 1 of 3
    19    low = mid + 1;  // search right20} else {21    high→ 2 = mid3 - 1;  // search left22}
    All 3 passes — pass 1 is the card above
    passmidhigh
    132
    232
    310
  6. low ← 2

    pass 1 of 7
    17    return mid;  // found18} else if (cmp-1 < 0) {19    low→ 2 = mid1 + 1;  // search right20} else {
    All 7 passes — pass 1 is the card above
    passcmpmidlow
    1-112
    2-334
    3-156
    4-2234
    5-2056
    6-1967
    7-1878
  7. if (cmp == 0)

    pass 1 of 3
    16if (cmp0 == 0) {17    return mid2;  // found18} else if (cmp < 0) {
    All 3 passes — pass 1 is the card above
    passmid
    12
    26
    30
  8. index ← 2

    43for (String name : searches) {44    int index→ 2 = searchByName(phonebook, nameCharlie);45    if (index >= 0) {
  9. c ← Contact[name=Charlie, phone=555-1003]

    pass 1 of 3
    44int index = searchByName(phonebook, name);45if (index2 >= 0) {46    Contact c→ Contact[name=Charlie, phone=555-1003] = phonebook[index]Contact[name=Charlie, phone=555-1003];47    System.out.println(nameCharlie + ": " + c.phone());48} else {
    outputCharlie: 555-1003
    All 3 passes — pass 1 is the card above
    passindexphonebook[index]namec
    12Contact[name=Charlie, phone=555-1003]CharlieContact[name=Charlie, phone=555-1003]
    26Contact[name=Grace, phone=555-1007]GraceContact[name=Grace, phone=555-1007]
    30Contact[name=Alice, phone=555-1001]AliceContact[name=Alice, phone=555-1001]
  10. index ← 6

    43for (String name : searches) {44    int index→ 6 = searchByName(phonebook, nameGrace);45    if (index >= 0) {
  11. index ← 0

    43for (String name : searches) {44    int index→ 0 = searchByName(phonebook, nameAlice);45    if (index >= 0) {
  12. return -1; // not found

    25    return -1;  // not found26}
  13. index ← -1

    43for (String name : searches) {44    int index→ -1 = searchByName(phonebook, nameZoe);45    if (index >= 0) {
  14. else

    47    System.out.println(name + ": " + c.phone());48} else {49    System.out.println(nameZoe + ": not found");50}
    outputZoe: not found

Exercise: Practical.java

Implement binary search to find the first occurrence of a duplicate value in a sorted array