简体   繁体   中英

Recursive binary search on ArrayList

I'm trying to do a recursive binary search on an ArrayList but not sure what the issue with my code is. I have a text file with a bunch of integer numbers that look like this:

217 320 550 212 12 17 3560 2999 211

The problem is that when I input a number to search the ArrayList, it always says the element does not exist, but I know it does!

        public static int binarySearch(List<Integer> arr, Integer l, Integer r, Integer x)
        {
            if (r>=l)
            {
                Integer mid = l + (r - l)/2;

                // If the element is present at the middle itself
                if ((arr.size()/2) == x)
                    return mid;

                // If element is smaller than mid, then it can only
                // be present in left subarray
                if ((arr.size()/2) > x)
                    return binarySearch(arr, l, mid-1, x);

                // Else the element can only be present in right
                // subarray
                return binarySearch(arr, mid+1, r, x);
            }
            // We reach here when element is not present in array
            return -1;
        }   
    }

Any help would be greatly appreciated, new programmer here!

The part where you check if the element is present is wrong, don't do this:

arr.size()/2 == x
arr.size()/2 > x

Instead, do this:

arr.get(mid) == x
arr.get(mid) > x

Because you're supposed to access the element at the mid position, not checking if half the list's size equals x .

Shouldn't you replace arr.size() with arr[mid] or something like that? Looks like you don't compare the value of an item, but rather the array size itself, which is constant and totally irrelevant.

You calculate mid , and then use arr.size() / 2 , instead...

Replace them with arr.get(mid) , something like this:

public static int binarySearch(final List<Integer> arr, final int l, final int r, final Integer x)
{
   if (r >= l)
   {
      final int mid = l + (r - l) / 2;

      // If the element is present at the middle itself
      if (x.equals(arr.get(mid)))
         return mid;

      // If element is smaller than mid, then it can only
      // be present in left subarray
      if (arr.get(mid) > x)
         return binarySearch(arr, l, mid - 1, x);

      // Else the element can only be present in right
      // subarray
      return binarySearch(arr, mid + 1, r, x);
   }
   // We reach here when element is not present in array
   return -1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM