// Source code example for "A Practical Introduction // to Data Structures and Algorithm Analysis" // by Clifford A. Shaffer, Prentice Hall, 1998. // Copyright 1998 by Clifford A. Shaffer // Hashtable driver class. Use some really simple hash // and probe functions for testing purposes. public class HashTable { private int M; private Elem[] T; private int h(int key) { return key % M; } private int p(int key, int slot) { return slot; } HashTable(int m) { M = m; T = new Elem[M]; } void hashInsert(Elem R) { // Insert record R into T int home; // Home position for R int pos = home = h(R.key()); // Initial position for (int i=1; T[pos] != null; i++) { pos = (home + p(R.key(), i)) % M; // Next pobe slot Assert.notFalse(T[pos].key() != R.key(), "Duplicates not allowed"); } T[pos] = R; // Insert R } Elem hashSearch(int K) { // Search for the record with key K int home; // Home position for K int pos = home = h(K); // Initial position for (int i = 1; (T[pos] != null) && (T[pos].key() != K); i++) pos = (home + p(K, i)) % M; // Next probe position if (T[pos] == null) return null; // K not in hash table else return T[pos]; // Found it } }