Interview(8)Dictionary and Tree
Dictionary - No Order
public class DictionaryDLNode implements Dictionary {
private List list; //store all items
private EqualityTester tester;
public DictionaryDLNode(){
this(new EqualityTesterDefault());
}
public DictionaryDLNode(EqualityTester t){
list = new ListDLNode(); tester = t;
}
public int getSize() { return list.getSize(); }
public boolean isEmpty() { return list.isEmpty(); }
public Entry find(Object key){
Iterator p = list.positions();
while(p.hasNext()){
Position pos = (Position) p.getNext();
Entry entry = (EntryDefault) pos.getElem();
if(tester.isEqualTo(entry.getKey(), key)){
return entry;
}
}
}
public Iterator findAll(Object key){
List list = new ListDLNode();
Iterator p = l.positions();
while(p.hasNext()){
Position pos = (Position)p.getNext();
Entry entry = (EntryDefault) pos.getElem();
if(tester.isEqualTo(entry.getKey(), key)){
list.insertLast(entry);
}
}
return new IteratorElement(list);
}
public Entry insert(Object key, Object value){
Entry entry = new EntryDefault(key, value); //create new Entry
list.insertFirst(entry);
return entry;
}
public Entry remove(Object key){
Iterator p = list.positions();
while(p.hasNext()){
Position pos = (Position) p.getNext();
Entry entry = (EntryDefault) pos.getElem();
if(tester.isEqualTo(entry.getKey()), key){
Entry oldEntry = entry;
list.remove(pos); //remove item
return oldEntry;
}
}
return null;
}
public Iterator entries() { return new IteratorElement(list); }
}
Dictionary - Order
Binary Search
Method: binSearch(S, low, high, key)
Inputs: search table S, low and high, Key
Outputs: s[low.. high], find the item for key
binSearch(S, 0, n-1, key)
{
if low > high, system can not find it
middle = (low + high) /2;
if key > S[middle].key, binSearch(S, middle+1, high, key);
if key < S[middle].key, binSearch(S, low, middle-1, key);
return middle; //hit the right item
}
Binary Search Tree
left tree should be lower than current parent key, right tree should be higher than current parent key.
AVL Tree
B Tree - TODO
Sorting
References:
Interview(8)Dictionary and Tree
猜你喜欢
转载自sillycat.iteye.com/blog/2387134
今日推荐
周排行