通过另一个数组二进制搜索数组的最佳方法是什么?

时间:2012-07-02 15:08:05

标签: java arrays string algorithm binary-search

在数组中进行二进制搜索的最佳方法是什么才能实际访问通过间接? 含义我有Integer[]存储String[]的索引,代表String[]的排序版本 例如。 Integer[] idxes= {5, 4, 0, 3 , 1, 2}这意味着String[5]String[idxes[0]]是按字典顺序排列的最低字符串。
我希望说明清楚 如果idexesString的一部分,那么String[] words通过int pos = Arrays.binarySearch(idexes, -1, new Comparator<Integer>(){ @Override public int compare(Integer o1, Integer o2) { if(o1 == -1){ return k.compareTo(words[o2]); } else{ return words[o1].compareTo(k); } } }); 进行二进制搜索的最佳方法是什么?

我所做的是以下内容:

k

其中words[]是搜索词,String[]是我前面提到的-1
这有效,但我不喜欢binarySearch api中传递的{{1}} 有没有更好的方法来解决这个问题?

1 个答案:

答案 0 :(得分:2)

class SortedListView extends AbstractList<String> implements RandomAccess {
  // stringArray, idxes should be fields, initialized in a constructor
  public int size() {
    return stringArray.length;
  }
  public String get(int index) {
    return stringArray[idxes[index]];
  }
};

然后,您可以Collections.binarySearch使用List

相关问题