jeudi 20 octobre 2016

Recursive search error

running into a silly error and I just don't see it. I've been looking at this for a while and don't see what I'm missing. I am recursively searching an array for a specific target number but once I get up to element [7] it begins returning -1. Thanks for taking a look fellas/ladies!

    public static void main(String[] args) 
    {
        int[] a = {1,25,2,6,4,3,23,30,32,14,11,8};
        Arrays.sort(a);
        int target = a[7];
        int first = a[0];
        int last = a.length;
        for(int i=0;i<a.length;i++)
        {
            System.out.print(" "+a[i]);
    }
        System.out.println("\n"+binarySearch(target,first,last,a));
    }
    public static int binarySearch(int target,int first, int last, int[] a)
    {
        int result;
        if(first>last)
            return -1;
        else
        {
            int mid = (first+last)/2;
            if(target == mid)
                result = mid;
            else if(target<a[mid])
                result = binarySearch(target,first,last-1,a);
            else
                result = binarySearch(target,mid+1,last,a);

        }
        return result;
    }

Aucun commentaire:

Enregistrer un commentaire