user19576524
user19576524

Reputation:

Using binary search to find the index of the target number

it is my first time to use this platform to ask questions. I wonder what is wrong with the following codes, which don't print out the index of the target number at the end of the main. What's wrong? Have a nice day for those who read this post.

public class binarySearch {
    public static void main(String[] args) {
        Scanner keyboard=new Scanner(System.in);
        int target,index;
        int [] numArray={1,4,6,7,8,10,14,16,17,26,30,35,38,41};

        System.out.print("What do you want to find?");
        target=keyboard.nextInt();
        index=binarySearch(numArray, target);
        System.out.println("The element is found at index:"+index);
    }

    static int binarySearch(int [] numArray, int target){
        int left=0;
        int right=numArray.length-1;
        int mid=(left+right)/2;
        while(left<=right){
            if(numArray[mid]==target){
                return mid;
            }else if(target<numArray[mid]){
                right=mid-1;
            }else{
                left=mid+1;
            }
        }
        return -1;
    }
}



Upvotes: 0

Views: 378

Answers (2)

DEVSHK
DEVSHK

Reputation: 863

Initial mid value after while condition

public class binarySearch {
    public static void main(String[] args) {
        Scanner keyboard=new Scanner(System.in);
        int target,index;
        int [] numArray={1,4,6,7,8,10,14,16,17,26,30,35,38,41};

        System.out.print("What do you want to find?");
        target=keyboard.nextInt();
        index=binarySearch(numArray, target);
        System.out.println("The element is found at index:"+index);
    }

    static int binarySearch(int [] numArray, int target){
        int left=0;
        int right=numArray.length-1;
        while(left<=right){
            int mid=left+(right-left)/2;
            if(numArray[mid]==target){
                return mid;
            }else if(target<numArray[mid]){
                right=mid-1;
            }else{
                left=mid+1;
            }
        }
        return -1;
    }
}

Upvotes: 0

Charchit Kapoor
Charchit Kapoor

Reputation: 9284

You are not re-calculating, mid within loop:

static int binarySearch(int [] numArray, int target) {
    int left = 0;
    int right = numArray.length - 1;
    int mid = (left + right) / 2;
    while (left <= right) {
        mid= (left + right) / 2;
        if (numArray[mid] == target) {
            return mid;
        } else if (target < numArray[mid]) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return -1;
}

Upvotes: 2

Related Questions