Added Binary Search.
--- a/src/jdict/AskWord.java Wed Jul 25 20:52:44 2007 +0200
+++ b/src/jdict/AskWord.java Wed Jul 25 21:21:15 2007 +0200
@@ -92,7 +92,9 @@
showSearch.setText(toSearch);
System.out.println("Serĉante: " + toSearch);
- results = index.SearchDefinition(toSearch);
+
+ /* Search the word */
+ results = index.BinarySearchDefinition(toSearch);
Results resultsform = new Results(results, myform);
}
--- a/src/jdict/DictIndex.java Wed Jul 25 20:52:44 2007 +0200
+++ b/src/jdict/DictIndex.java Wed Jul 25 21:21:15 2007 +0200
@@ -12,11 +12,35 @@
String defs_basename;
int index_id;
+ int top_index;
+
public DictIndex(String dictname)
{
index_basename = "/dicts/x-" + dictname + ".index";
defs = new DictDefs(dictname);
in = new BlockFile(index_basename);
+ get_top_index();
+ }
+
+ public void get_top_index()
+ {
+ InputStream bfile = getClass().getResourceAsStream("/dicts/TOPINDEX");
+ /* 10 bytes is enough for a simple int */
+ byte array[] = new byte[10];
+ int total;
+ try {
+ total = bfile.read(array, 0, 10);
+ } catch (IOException e)
+ {
+ System.out.println("Cannot open TOPINDEX.");
+ top_index = 0;
+ return;
+ }
+ /* This will have '\n' */
+ String str = new String(array, 0, total - 1 /* - \n */);
+ top_index = Integer.parseInt(str);
+ System.out.println("Top Index: " +
+ new Integer(top_index).toString());
}
public String getName()
@@ -256,4 +280,52 @@
return results;
}
+
+ public Vector BinarySearchDefinition(String word)
+ {
+ Vector results = new Vector();
+ int pivot = top_index / 2;
+ int step = top_index / 2;
+
+ String test;
+ do
+ {
+ System.out.println("Pivoting to " +
+ new Integer(pivot).toString());
+ try {
+ in.seekFromStart(pivot);
+ } catch (IOException e)
+ {
+ System.out.println("Seek from start error");
+ return results;
+ }
+ readUntilNewLine();
+ test = getName();
+ if (test == null)
+ break;
+ int comparision = word.compareTo(test);
+ if (comparision == 0)
+ {
+ int offset = getOffset();
+ int length = getLength();
+ System.out.println("Definition for " + word + " at " +
+ new Integer(offset).toString() + " length " +
+ new Integer(length).toString());
+ String definition = defs.getDefinition(offset, length);
+
+ results.addElement(definition);
+ return results;
+ } else if (comparision < 0)
+ {
+ step = step / 2;
+ pivot = pivot - step;
+ } else if (comparision > 0)
+ {
+ step = step / 2;
+ pivot = pivot + step;
+ }
+ } while (step > 0);
+
+ return results;
+ }
}