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); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter