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)。