#What's wrong with the code?

7 messages · Page 1 of 1 (latest)

gaunt zephyr
#

import java.util.Scanner;

public class hw2 {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("enter no of elements in the array:");
    int n = sc.nextInt();
    System.out.println("enter 5 no of elements in ascending order::");
    int a[]= new int[n];
    for(int i=0;i<a.length;i++) {
        a[i]= sc.nextInt();
        
        
    }
    System.out.println("Enter the elments to search:");
    int s= sc.nextInt();
    int key=s;
    int first=a[0];
    int last = a[n-1];
    int res=binser(a,s,first,last);
    if(res!=-1) {
        System.out.println("the "+key+" is present at index "+res);
    }
    else {
        System.out.println("the "+key+" is not present in the array");
    }

}
public static int binser(int a[],int s,int start,int end) {
    if(end>=start && start<=a.length-1) {
        int mid = start+(end-start)/2;
        if(a[mid]==s) {
            return mid;
        }
        if(a[mid]>s) {
            return binser(a,s,start,mid-1);
        }
        return binser(a,s,mid+1,end);
        
    }
    return -1;
}

}
OUTPUT:
enter no of elements in the array:
5
enter 5 no of elements in ascending order::
11
22
33
44
55
Enter the elments to search:
33
the 33 is not present in the array

fringe pantherBOT
#

This post has been reserved for your question.

Hey @gaunt zephyr! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

vague bone
#

have you written binary search correctly

snow night
#

Nope, they have not

#

the cursor "mid" should start as arraylength /2, then update by either the addition or subtraction of arraylength / 4^x, x being the recursion depth.

#

here, it updates according to the first and last elements, not their indexes