Search code examples
javadata-structureswhile-loopbinary-search

My binary search for seeing if an integer is in an array is looping forever, does anyone know why? (in Java)


My binary search for seeing if an integer is in an array is looping forever, does anyone know why this might be occurring? By the way, I am using a binary search for the first time.

My Java code is here:

import java.util.Scanner;

public class testBeforeLearning {
        private int[] array;
        private int target;

        public testBeforeLearning(int[] array, int target){
            this.array = array;
        }

        private int low;
        private int high;
        private int mid;

        public Boolean actualSearch(){
            low = 0;
            high = array.length - 1;

            while (target != array[mid]){
                mid = (low + high)/2;

                if (target == array[mid]){
                    return true;
                }

                else if(target > array[mid]){
                    low = mid + 1;
                }
                else if (target < array[mid]){
                    high = mid - 1;
                }
            }
            return false;
        }

        public static void main(String[] args){

            Scanner input = new Scanner(System.in);

            int[] dataSet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

            System.out.println("Please input a number you want to search for in the array:\n");

            int target = input.nextInt();

            testBeforeLearning binarySearch = new testBeforeLearning(dataSet, target);
            System.out.println(binarySearch.actualSearch());

    }
}


For some reason, my lower and upper bounds don't seem to be increasing or decreasing, and I am not sure why, does anyone have any ideas why?

Thanks!


Solution

  • you've set your while condition to be target != array[mid]. But since target is uninitialized (defaults to 0) and 0 does not exist in the array, it will go on forever. you have to set the value of target in testBeforeLearning. On a side note, you should probably also make the while condition low <= high.