0

Why is my code not working though I've tried dry running it 1000 times, but still I'm not able to find my doubt, maybe I'm short of the knowledge which will help me find the mistake, can anybody help me with this?

package _08_Arrays;

public class _04_Binary_Search {
    

public static void main(String[] args) {
    int arr[] = { 5, 3, 2, 4, 1 };
    int target = 2;
    SortArray(arr);
    System.out.print(BinarySearch(arr, target));
}

public static int BinarySearch(int[] arr, int target) {
    int s = 0; // I took int s=arr[0] which will provide inconvenience in case if I want do s++
                // or s--, it will increase the value of the element in the array by one.
    int n = arr.length;
    int e = n - 1;
    for(;s<=e;) {
        int mid=(s+e)/2;
        if(arr[mid]>target) {
            e=mid-1;
        } else if(arr[mid]<target) {
            s=mid+1;
        } else {
            return mid;
        }
    }
    return -1;
}

public static void SortArray(int[] arr) {
    // TODO Auto-generated method stub
    int idx=-1;
    int sort=0;
    for(int j=0;j<arr.length;j++) {
        int min=Integer.MAX_VALUE;
        for(int i=sort;i<arr.length;i++) {
            if(arr[i]<min) {
                min=arr[i];
                idx=i;
            }
        }
        int temp=arr[sort];
        arr[sort]=min;
        arr[idx]=temp;
        sort++;
        }
}

}

I tried to get the index of the element which I tend to pass in the target element, but I'm getting different index of the element in the array which is different from the actual index of elements of the array.

7
  • I tried running your code and didn't see any problems. Commented Jul 9, 2024 at 11:14
  • 3
    There’s no point in prepending a sort operation to the Binary Search implementation you want to test. The search will return an index to the sorted array, so use a sorted array in the first place. The code as posted, produces index one, not zero, which is the expected index, as the previous commenter already said. Commented Jul 9, 2024 at 11:18
  • dsa is about something else. Removed tag. Commented Jul 9, 2024 at 12:17
  • "I'm getting 0 always ": I cannot reproduce that. Running your code I get 1 as output. Voting to close as not reproducible. Commented Jul 9, 2024 at 12:28
  • Please see carefully, run for different values of targets, for target as 1 in array { 5, 3, 2, 4, 1 }, it is giving 0 as the index in the array, for target as 4 in array { 5, 3, 2, 4, 1 }, it is giving 3 as the index in the array, for target as 2 in array { 5, 3, 2, 4, 1 }, it is giving 1, etc. which are obviously not the desirable output. Commented Jul 10, 2024 at 11:59

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.