hash table and heaps
DESCRIPTION
Basic info about hash and heaping techniquesTRANSCRIPT
Hash Table and Heaps
Still With Tree Traversalvoid BST::levelOrder(){
Queue<node*> q;
q.enqueue(root);
while(!q.isEmpty()){
node *p = q.dequeue();
cout<<p->item<<“ “;
if(p->left!=NULL)
q.enqueue(p->left);
if(p->right!=NULL)
q.enqueue(p->right);
}
}
Still On Search
Through the AVL, search was improved to log n. But we perform better?
Hash TableHash function/ HashingAn array of some fixed containing the keysEach key is mapped into some number in
range 0 to H_SIZE-1This mapping is called a hash function
Hash Table10
2
4
8
Hash Table
Hash Functionsitem % H_SIZEProblematic
Might run out of space (array)An item might already exist (collision)Solutions
Closed hashing (linear probing)Open hashing
Hash Table10
12
34
4
14
74
8
18
Hash Table
Closed hashingpos = x % H_SIZE;
while(??){
pos++;
}
Items[pos] = x;
Hash Table
The keys of the hash table are normally strings
Hash functionsSum up the ASCII codes of the characters
before performing %(st[0] + 27*st[1] + 729*st[2]) % H_SIZE
Hash Table
Open hashing Array of linked-lists
Priority Queue (Heap)A data structure allows at least the
following two operationsinsert – similar to enqueuedeleteMin/deleteMax – heap’s equivalent of
dequeueImplementation
Represent as a binary tree that is completely filled, with the exception of the bottom level
Completely filled from left to right
Simplest way is to use an array
Heap
Heap
Heap order propertyEvery node X, the key in the parent of X is
smaller (or equal to) the key in XWith the exception of the root (which has no
parent)min-heap
Heap
Heap
Insertion (refer to board)
Heapbool Heap::insert(int x){
if(isFull())
return false;
else{
int i = size++;
while(items[i/2]>x){
items[i] = items[i/2];
i/=2;
}
items[i] = x;
}
Heap
deleteMin (refer to board)
Heapbool Heap::deleteMin(){
if(isEmpty())
return false;
else{
last = items[size--];
for(int i=1; i*2<=size; i=child){
child = i*2;
if(child!=size && items[child+1] < items[child])
child++;
if(last > items[child])
items[i] = items[child];
else
break;
}
return true;
}
}