hash table and heaps

17
Hash Table and Heaps

Upload: katang-isip

Post on 06-May-2015

2.428 views

Category:

Education


0 download

DESCRIPTION

Basic info about hash and heaping techniques

TRANSCRIPT

Page 1: Hash table and heaps

Hash Table and Heaps

Page 2: 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);

}

}

Page 3: Hash table and heaps

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

Page 4: Hash table and heaps

Hash Table10

2

4

8

Page 5: Hash table and heaps

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

Page 6: Hash table and heaps

Hash Table10

12

34

4

14

74

8

18

Page 7: Hash table and heaps

Hash Table

Closed hashingpos = x % H_SIZE;

while(??){

pos++;

}

Items[pos] = x;

Page 8: Hash table and heaps

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

Page 9: Hash table and heaps

Hash Table

Open hashing Array of linked-lists

Page 10: Hash table and heaps

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

Page 11: Hash table and heaps

Heap

Page 12: Hash table and heaps

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

Page 13: Hash table and heaps

Heap

Page 14: Hash table and heaps

Heap

Insertion (refer to board)

Page 15: Hash table and heaps

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;

}

Page 16: Hash table and heaps

Heap

deleteMin (refer to board)

Page 17: Hash table and heaps

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;

}

}