Hashtables are efficient implementation of array data structure (an associative array) that stores key/value pairs and searched by the key value.It uses a floating-point value, a string, another array, or a structure as the index. A hashtable has 2 elements, a key set and a value set.And find a way to represent and keys should always map to the appropriate.Next use a hash function that is perfect for you.A hash function depends upon the criteria, could be anything.
C language is not provided with keyed arrays , in order to access an element is by its index number.
Eg:- students[66];
I have provided the hashtable code in java :
public class HashEntry {
private int key;
private int value;
HashEntry(int key, int value) {
this.key = key;
this.value = value;
}
public int getKey() {
return key;
}
public int getValue() {
return value;
}
}
public class HashMap {
private final static int TABLE_SIZE = 100;
HashEntry[] table;
HashMap() {
table = new HashEntry[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
table[i] = null;
}
public int get(int key) {
int hash = (key % TABLE_SIZE);
while (table[hash] != null && table[hash].getKey() != key)
hash = (hash + 1) % TABLE_SIZE;
if (table[hash] == null)
return -1;
else
return table[hash].getValue();
}
public void put(int key, int value) {
int hash = (key % TABLE_SIZE);
while (table[hash] != null && table[hash].getKey() != key)
hash = (hash + 1) % TABLE_SIZE;
table[hash] = new HashEntry(key, value);
}
}
No comments:
Post a Comment