在java中搜索排序的字符串数组中的给定字符串

时间:2022-03-28 07:08:53

I have written a program that searches for a String in a Sorted Array of Strings. My Program works fine except for the times when there are empty strings in my array. Below is the code:

我编写了一个程序,用于搜索字符串排序数组中的字符串。我的程序工作正常,除了我的数组中有空字符串的时候。以下是代码:

public class StringSearch {

public static int binarySearchString(String[] s, String search)
{   

     int low = 0;
     int high = s.length-1;
     int mid;

     while(low<=high)
     {  mid = (high+low)/2;
         if(search.compareTo(s[mid])<0)
             high = mid-1;
         else if(search.compareTo(s[mid])>0)
             low = mid+1;
         else
             return mid;

     }
     return -1;

 }
 public static void main(String[] args)
 {

     String[] str = {"abc", "", "def", "ijk", "mnop", "xyz"};
     String toSearch = new String("ijk");
     int result = binarySearchString(str, toSearch);
       if(result == -1)
          System.out.println("String not found!!");
       else
          System.out.println("String found at array index:" + result);
 }

 }

Where am I making a mistake?

我在哪里弄错了?

1 个解决方案

#1


1  

Your array is not actually sorted: the empty string should come first in the array.

您的数组实际上没有排序:空字符串应该在数组中排在第一位。

However, having said that, your test case of "ijk" should still work as it is after the mid point so avoids the unsorted section of the array.

但是,话虽如此,你的“ijk”测试用例应该仍然可以在中点之后工作,因此避免了数组的未排序部分。

So I ran your code and it correctly returns

所以我运行你的代码,它正确返回

String found at array index:3

It does not work in searching for "".

它不适用于搜索“”。

Add Arrays.sort(str) before the call binarySearchString.

在调用binarySearchString之前添加Arrays.sort(str)。

#1


1  

Your array is not actually sorted: the empty string should come first in the array.

您的数组实际上没有排序:空字符串应该在数组中排在第一位。

However, having said that, your test case of "ijk" should still work as it is after the mid point so avoids the unsorted section of the array.

但是,话虽如此,你的“ijk”测试用例应该仍然可以在中点之后工作,因此避免了数组的未排序部分。

So I ran your code and it correctly returns

所以我运行你的代码,它正确返回

String found at array index:3

It does not work in searching for "".

它不适用于搜索“”。

Add Arrays.sort(str) before the call binarySearchString.

在调用binarySearchString之前添加Arrays.sort(str)。