Linear probing

PHOTO EMBED

Sun Jun 09 2024 10:24:07 GMT+0000 (Coordinated Universal Time)

Saved by @login

public class LinearProbingHashTable {
    private String[] keys;
    private String[] values;
    private int size;
    private int capacity;

    // Constructor
    public LinearProbingHashTable(int capacity) {
        this.capacity = capacity;
        this.keys = new String[capacity];
        this.values = new String[capacity];
        this.size = 0;
    }

    // Hash function (simple demonstration using string length)
    private int hash(String key) {
        return key.length() % capacity;
    }

    // Insert key-value pair into the hash table
    public void put(String key, String value) {
        if (key == null || value == null) {
            throw new IllegalArgumentException("Key or value cannot be null.");
        }
        
        int index = hash(key);
        while (keys[index] != null) {
            if (keys[index].equals(key)) {
                // Update value if key already exists
                values[index] = value;
                return;
            }
            // Linear probing to find next available slot
            index = (index + 1) % capacity;
        }
        // Insert key-value pair
        keys[index] = key;
        values[index] = value;
        size++;
    }

    // Get value associated with the given key
    public String get(String key) {
        int index = hash(key);
        while (keys[index] != null) {
            if (keys[index].equals(key)) {
                return values[index];
            }
            // Linear probing to search for key
            index = (index + 1) % capacity;
        }
        return null; // Key not found
    }

    // Display hash table contents
    public void display() {
        for (int i = 0; i < capacity; i++) {
            if (keys[i] != null) {
                System.out.println("Key: " + keys[i] + ", Value: " + values[i]);
            }
        }
    }

    public static void main(String[] args) {
        LinearProbingHashTable hashTable = new LinearProbingHashTable(10);
        
        // Insert key-value pairs
        hashTable.put("John", "Doe");
        hashTable.put("Alice", "Smith");
        hashTable.put("Bob", "Johnson");
        hashTable.put("Charlie", "Brown");
        
        // Display hash table contents
        hashTable.display();
        
        // Retrieve values
        System.out.println("Value associated with 'John': " + hashTable.get("John"));
        System.out.println("Value associated with 'Alice': " + hashTable.get("Alice"));
        System.out.println("Value associated with 'Bob': " + hashTable.get("Bob"));
        System.out.println("Value associated with 'Charlie': " + hashTable.get("Charlie"));
        System.out.println("Value associated with 'Dave': " + hashTable.get("Dave")); // Not found
    }
}
content_copyCOPY