Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Logic Error: Binary search fails with more than two elements in a string array

The objective is to return the index of an element in a string array if present. The method uses a basic binary search using compareTo statements. With more than two elements in a tested array, the method will not detect the present element and return -1. The Java code this question is referring to is below. How do I make the binary search method work as intended?

   public static int binarySearch(String[] array, String x) {
        int high = array.length - 1;
        int low = 0;

        while (low <= high) {

            int mid = low + (high - low) / 2;

            if (x.compareTo(array[mid]) == 0) {
                return mid;
            }
            if (x.compareTo(array[mid]) > 0) {
                low = mid + 1;
            }
            else {
                high = mid - 1;
            }
        }
        return -1;
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

add an extra variable and set it to -1;

int loc=-1;

change the code

int mid=low+(high-low)/2;

to

 int mid=(low+high)/2;
 if(x.compareTo(array[mid]==0)
 {
  loc=mid;
  break;
 }
 else if(x<array[mid])
 {
  last=mid-1;
 }
 else
 {
   low=mid+1;
 }

then

if(loc>=0)
{
 System.out.println(loc+1);
} 
else
{
  System.out.println("no element");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading