in the java search_在java中搜索排序的字符串數組中的給定字符串

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值