java - Binary search with word prefix string out of bounds -


i have program creates class dictionary, in populates , arraylist of strings words given command line argument(in alphabetical order, different lengths). anyway, need implement binary search prefix in dictionary part of backtracking method. run problems when prefix longer word in dictionary---i tried adjust binary search situation producing incorrect results. don't understand binary search enough fix issue. if don't account issue of prefix being longer word, .substring produces string indexoutofbounds. appreciated.

public int searchprefix(string prefixkey){     int minindex=0;     int maxindex= newdictionary.size()-1;     return searchprefix( prefixkey, minindex,maxindex); }  public int searchprefix(string prefixkey, int minindex, int maxindex){     if(minindex>maxindex){         return-1;     }     int midindex=(maxindex-minindex)/2+minindex;     if (prefixkey.length()>newdictionary.get(midindex).length()){         return searchprefix( prefixkey, midindex+1,maxindex);     }     else if(newdictionary.get(midindex).length(<prefixkey.length()&&newdictionary.get(midindex).compareto(prefixkey.substring(0,newdictionary.get(midindex).length()))>0){         return searchprefix(prefixkey,minindex,maxindex);     }     else if(newdictionary.get(midindex).substring(0,prefixkey.length()).compareto(prefixkey)>0){         return searchprefix(prefixkey,minindex,maxindex-1);     }     else if(newdictionary.get(midindex).length()<prefixkey.length()&&newdictionary.get(midindex).compareto(prefixkey.substring(0,newdictionary.get(midindex).length()))<0){         return searchprefix(prefixkey,minindex,maxindex);     }     else if(newdictionary.get(midindex).substring(0,prefixkey.length()).compareto(prefixkey)<0){         return searchprefix( prefixkey, midindex+1,maxindex);     }     else          return midindex; } 

have taken binarysearch method collections class , modified per need.

private static int binarysearch(list<string> list, string key) {     int low = 0;     int high = list.size() - 1;     while (low <= high) {         int mid = (low + high) >>> 1;          string midval = list.get(mid);          int cmp = -1;          if (midval.length() > key.length())             cmp = midval.substring(0, key.length()).compareto(key);         else             cmp = key.substring(0, midval.length()).compareto(midval) * -1;          if (cmp < 0)             low = mid + 1;         else if (cmp > 0)             high = mid - 1;         else             return mid; // key found     }     return -1; // key not found } 

hope you.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -