hashing i assess

PHOTO EMBED

Sat May 04 2024 05:00:09 GMT+0000 (Coordinated Universal Time)

Saved by @cms

import java.util.Scanner;

public class QuadraticProbing {

    public static int hashFunction(int key, int size) {
        return key % size;
    }

    public static void insert(int key, int[] hashTable, int size) {
        int index = hashFunction(key, size);
        if (hashTable[index] == -1) {
            hashTable[index] = key;
        } else {
            int i = 1;
            while (true) {
                int newIndex = (index + i * i) % size;
                if (hashTable[newIndex] == -1) {
                    hashTable[newIndex] = key;
                    break;
                }
                i++;
            }
        }
    }

    public static void display(int[] hashTable) {
        for (int i = 0; i < hashTable.length; i++) {
            if (hashTable[i] == -1) {
                System.out.println(" Element at position " + i + ": -1");
            } else {
                System.out.println(" Element at position " + i + ": " + hashTable[i]);
            }
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the size of the hash table:");
        int size = scanner.nextInt();
        System.out.println("Enter the number of elements:");
        int n = scanner.nextInt();

        int[] hashTable = new int[size];
        for (int i = 0; i < size; i++) {
            hashTable[i] = -1;
        }

        System.out.println("Enter the Elements:");
        for (int i = 0; i < n; i++) {
            int key = scanner.nextInt();
            insert(key, hashTable, size);
        }

        System.out.println("\nThe elements in the array are:");
        display(hashTable);
    }
}
content_copyCOPY