2016-06-09 83 views
-1

我已經編寫了一個程序,用於在排序的字符串數組中搜索字符串。我的程序工作正常,除了數組中有空字符串的時候。以下是代碼:在java中排序的字符串數組中搜索給定的字符串

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); 
} 

} 

我在哪裏犯錯?

+1

二進制搜索將無法處理未排序的數組。 – MikeCAT

+1

請解釋_「除了空串以外的時間_」。怎麼了?如果數組已排序,空字符串在哪裏?你是如何對陣列進行排序的? –

+1

Techincally沒有排序,如果有一個空白的字符串在那裏隨機... – 3kings

回答

1

您的數組實際上沒有排序:空字符串應該先排在數組中。

但是,話說回來,你的「ijk」測試用例應該仍然在中點之後工作,所以避免了未排序的數組部分。

所以我跑你的代碼,並正確地返回

String found at array index:3 

它不會在搜索「」工作。

在呼叫binarySearchString之前加上Arrays.sort(str)

+0

我的不好:(謝謝 – BKodwani