/** * Lab6 Solution. * * @author M.Imtiaz ur rahaman. * @version 15-Sep-02. */ public class StringArray { private String[] wordlist = null; // The following variables are used to restrict the search in the array. private int head; private int tail; private int mid; /** * Constructors for objects of class StringArray */ // Create an empty wordlist. public StringArray() { wordlist = null; head = tail = mid = 0; } // Initialize the wordlist with the given array. public StringArray(String[] ss) { wordlist = new String[ss.length]; for(int i = 0; i < ss.length; i++) { wordlist[i] = ss[i]; } head = 0; tail = wordlist.length-1; mid = (head + tail)/2; } // Print the entire wordlist. public void showWordList() { if(wordlist == null) { System.out.println(""); return; } for(int i=0; i tail) { head = 0; tail = wordlist.length-1; mid = (head+tail)/2; return -1; } int value = str.compareTo(wordlist[mid]); if(value == 0) { int retvalue = mid; head = 0; tail = wordlist.length-1; mid = (head+tail)/2; return retvalue; } else { if(value < 0) { tail = mid-1; mid = (head+tail)/2; return binarySearch(str); } else { head = mid+1; mid = (head+tail)/2; return binarySearch(str); } } } /* * Search for the string "str" in the wordlist. * If caseIgnore == false then it becomes a case sensitive search * and just calls the above binarysearch(str) else do a case * insensitive search. */ public int binarySearch(String str, boolean caseIgnore) { if(caseIgnore == false) return binarySearch(str); if(wordlist == null) return -1; if(head > tail) { head = 0; tail = wordlist.length-1; mid = (head+tail)/2; return -1; } int value = str.compareToIgnoreCase(wordlist[mid]); if(value == 0) { int retvalue = mid; head = 0; tail = wordlist.length-1; mid = (head+tail)/2; return retvalue; } else { if(value < 0) { tail = mid-1; mid = (head+tail)/2; return binarySearch(str,true); } else { head = mid+1; mid = (head+tail)/2; return binarySearch(str,true); } } } }