注意,1,"" 和 " "。是不同的,空字符串指的是"";
2,注意String的compareTo。小于是指<0.并不是==-1;
仔细观察代码中注释掉的那一行错在哪里。
import java.util.*; public class Finder { public static int findString(String[] a,int n, String key){ int left = 0; int right = a.length - 1; while(left <= right){ int mid = (left + right) / 2; while(mid < right && a[mid] == "" ){ mid++; } while(mid > left && a[mid] == "") { mid--; } if(key.equals(a[mid])) return mid; //else if(key.compareTo(a[mid]) == -1){ else if(key.compareTo(a[mid]) < 0){ right = mid -1; } else { left = mid + 1; } } return -1; } }