0% found this document useful (0 votes)
8 views18 pages

Linear Probing

The document contains implementations of various data structures and algorithms in Java, including Linear Probing, Quadratic Probing, AVL Trees, and M-Way Trees. Each section provides a detailed code example for inserting, displaying, and managing the respective data structure, along with user input for dynamic operations. The outputs demonstrate the functionality of these data structures through sample inputs and their resulting configurations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views18 pages

Linear Probing

The document contains implementations of various data structures and algorithms in Java, including Linear Probing, Quadratic Probing, AVL Trees, and M-Way Trees. Each section provides a detailed code example for inserting, displaying, and managing the respective data structure, along with user input for dynamic operations. The outputs demonstrate the functionality of these data structures through sample inputs and their resulting configurations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Linear Probing

import java.util.Scanner;

public class LinearProbing {

static int size = 10; // Define the size of the hash table
static int[] hashTable = new int[size];

// Method to initialize the hash table


static void initializeHashTable() {
for (int i = 0; i < size; i++) {
hashTable[i] = -1; // -1 indicates an empty slot
}
}

// Hash function to get the index


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

// Linear probing method for insertion


static void insert(int key) {
int index = hashFunction(key);

// Check for an empty slot using linear probing


int originalIndex = index;
while (hashTable[index] != -1) {
index = (index + 1) % size; // Linear probing
if (index == originalIndex) {
System.out.println("Hash table is full!");
return;
}
}
hashTable[index] = key;
System.out.println("Inserted " + key + " at index " + index);
}

// Method to display the hash table


static void displayHashTable() {
System.out.println("Hash Table:");
for (int i = 0; i < size; i++) {
System.out.println("Index " + i + ": " + hashTable[i]);
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Initialize the hash table


initializeHashTable();
System.out.println("Enter the elements separated by space:");
String input = scanner.nextLine();
String[] elements = input.split(" "); // Split input by spaces

// Insert elements into the hash table


for (String element : elements) {
insert(Integer.parseInt(element));
}
// Display the hash table
displayHashTable();

scanner.close();
}
}

Output:
Enter the elements separated by space:
263149
Inserted 2 at index 2
Inserted 6 at index 6
Inserted 3 at index 3
Inserted 1 at index 1
Inserted 4 at index 4
Inserted 9 at index 9
Hash Table:
Index 0: -1
Index 1: 1
Index 2: 2
Index 3: 3
Index 4: 4
Index 5: -1
Index 6: 6
Index 7: -1
Index 8: -1
Index 9: 9
Quadratic Probing

import java.util.Scanner;

public class QuadraticProbing {

static int size = 10; // Define the size of the hash table
static int[] hashTable = new int[size];

// Initialize the hash table


static void initializeHashTable() {
for (int i = 0; i < size; i++) {
hashTable[i] = -1; // -1 indicates an empty slot
}
}

// Hash function
static int hashFunction(int key) {
return key % size;
}

// Quadratic probing method for insertion


static void insert(int key) {
int index = hashFunction(key);
int i = 0;
int originalIndex = index;

// Find an empty slot using quadratic probing


while (hashTable[index] != -1) {
i++;
index = (originalIndex + i * i) % size; // Quadratic probing

if (index == originalIndex) {
System.out.println("Hash table is full!");
return;
}
}
hashTable[index] = key;
System.out.println("Inserted " + key + " at index " + index);
}

// Display the hash table


static void displayHashTable() {
System.out.println("Hash Table:");
for (int i = 0; i < size; i++) {
System.out.println("Index " + i + ": " + hashTable[i]);
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Initialize the hash table


initializeHashTable();

System.out.println("Enter the elements separated by space:");


String input = scanner.nextLine();
String[] elements = input.split(" "); // Split input by spaces

// Insert elements using Quadratic Probing


for (String element : elements) {
insert(Integer.parseInt(element));
}

// Display the hash table


displayHashTable();

scanner.close();
}
}

Output:
Enter the elements separated by space:
5 10 15 20 20 25
Inserted 5 at index 5
Inserted 10 at index 0
Inserted 15 at index 6
Inserted 20 at index 1
Inserted 20 at index 4
Inserted 25 at index 9
Hash Table:
Index 0: 10
Index 1: 20
Index 2: -1
Index 3: -1
Index 4: 20
Index 5: 5
Index 6: 15
Index 7: -1
Index 8: -1
Index 9: 25
BST To AVL
import java.util.Scanner;

class AVLTree {
// Node class defined as a static nested class
static class Node {
int val;
Node left, right;
int height;

public Node(int val) {


this.val = val;
this.left = null;
this.right = null;
this.height = 1; // New node height is set to 1
}
}

private int rotationCount = 0; // Counter for rotations

// Get the height of the tree


private int height(Node node) {
return (node == null) ? 0 : node.height;
}

// Get the balance factor of a node


private int getBalance(Node node) {
return (node == null) ? 0 : height(node.left) - height(node.right);
}

// Perform right rotation


private Node rightRotate(Node y) {
rotationCount++; // Increment rotation count
Node x = y.left;
Node T = x.right;

// Perform rotation
x.right = y;
y.left = T;

// Update heights
y.height = Math.max(height(y.left), height(y.right)) + 1;
x.height = Math.max(height(x.left), height(x.right)) + 1;

return x; // New root


}

// Perform left rotation


private Node leftRotate(Node x) {
rotationCount++; // Increment rotation count
Node y = x.right;
Node T = y.left;

// Perform rotation
y.left = x;
x.right = T;

// Update heights
x.height = Math.max(height(x.left), height(x.right)) + 1;
y.height = Math.max(height(y.left), height(y.right)) + 1;

return y; // New root


}

// Insert a node dynamically into the AVL tree


public Node insert(Node root, int key) {
// Standard BST insertion
if (root == null) {
return new Node(key);
}

if (key < root.val) {


root.left = insert(root.left, key);
} else if (key > root.val) {
root.right = insert(root.right, key);
} else {
// Duplicates are not allowed
return root;
}

// Update height of current node


root.height = 1 + Math.max(height(root.left), height(root.right));

// Get the balance factor


int balance = getBalance(root);

// Perform rotations to balance the tree


if (balance > 1 && key < root.left.val) { // Left-Left case
return rightRotate(root);
}

if (balance < -1 && key > root.right.val) { // Right-Right case


return leftRotate(root);
}

if (balance > 1 && key > root.left.val) { // Left-Right case


root.left = leftRotate(root.left);
return rightRotate(root);
}

if (balance < -1 && key < root.right.val) { // Right-Left case


root.right = rightRotate(root.right);
return leftRotate(root);
}

return root; // Return unchanged node


}

// Convert BST to AVL tree dynamically


public Node bstToAVL(Node bstRoot) {
Node avlRoot = null;

// Perform in-order traversal of BST and insert into AVL tree


avlRoot = insertNodes(avlRoot, bstRoot);

return avlRoot;
}

private Node insertNodes(Node avlRoot, Node bstNode) {


if (bstNode == null) {
return avlRoot;
}

// Traverse BST in in-order fashion and insert into AVL tree


avlRoot = insertNodes(avlRoot, bstNode.left);
avlRoot = insert(avlRoot, bstNode.val);
avlRoot = insertNodes(avlRoot, bstNode.right);

return avlRoot;
}

// In-order traversal to print the tree


public void inOrderTraversal(Node root) {
if (root == null) {
return;
}
inOrderTraversal(root.left);
System.out.print(root.val + " ");
inOrderTraversal(root.right);
}

// Display tree structure


public void display(Node root, String indent, boolean isLeft) {
if (root == null) {
return;
}

if (isLeft) {
System.out.println(indent + "L---- " + root.val);
indent += "| ";
} else {
System.out.println(indent + "R---- " + root.val);
indent += " ";
}

display(root.left, indent, true);


display(root.right, indent, false);
}

// Getter for rotation count


public int getRotationCount() {
return rotationCount;
}
}
public class BSTToAVL {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
AVLTree avlTree = new AVLTree();

// Dynamic input for BST


System.out.println("Enter the number of nodes for the BST:");
int n = scanner.nextInt();

System.out.println("Enter the values of the nodes:");


AVLTree.Node bstRoot = null;
for (int i = 0; i < n; i++) {
int value = scanner.nextInt();
bstRoot = avlTree.insert(bstRoot, value);
}

// Convert BST to AVL dynamically


AVLTree.Node avlRoot = avlTree.bstToAVL(bstRoot);

// Print in-order traversal of AVL tree


System.out.print("In-order traversal of the AVL tree: ");
avlTree.inOrderTraversal(avlRoot);
System.out.println();

// Display AVL tree structure


System.out.println("AVL Tree structure:");
avlTree.display(avlRoot, "", false);

// Print the number of rotations


System.out.println("Number of rotations performed: " + avlTree.getRotationCount());

scanner.close();
}
}

Output:
Enter the number of nodes for the BST:
6
Enter the values of the nodes:
123456
In-order traversal of the AVL tree: 1 2 3 4 5 6
AVL Tree structure:
R---- 4
L---- 2
| L---- 1
| R---- 3
R---- 5
R---- 6
Number of rotations performed: 6
M-Way-Tree
import java.util.Arrays;
import java.util.Scanner;

class BTreeNode {
int[] keys; // Stores keys in the node
BTreeNode[] children; // Stores child pointers
int keyCount; // Number of keys currently in the node
boolean isLeaf; // Flag to check if it's a leaf node

public BTreeNode(int m, boolean isLeaf) {


this.isLeaf = isLeaf;
this.keys = new int[m - 1]; // Max (m-1) keys
this.children = new BTreeNode[m]; // Max m children
this.keyCount = 0;
}
}

class BTree {
private BTreeNode root;
private final int m; // Max number of children per node

public BTree(int m) {
this.m = m;
this.root = new BTreeNode(m, true); // Root starts as a leaf
}

public void insert(int key) {


BTreeNode r = root;
if (r.keyCount == m - 1) { // Root is full, need to split
BTreeNode newRoot = new BTreeNode(m, false);
newRoot.children[0] = root;
splitChild(newRoot, 0, root);
root = newRoot;
}
insertNonFull(root, key);
}

private void insertNonFull(BTreeNode node, int key) {


int i = node.keyCount - 1;
if (node.isLeaf) { // Insert in a leaf node
while (i >= 0 && key < node.keys[i]) {
node.keys[i + 1] = node.keys[i];
i--;
}
node.keys[i + 1] = key;
node.keyCount++;
} else { // Insert in an internal node
while (i >= 0 && key < node.keys[i]) {
i--;
}
i++;
if (node.children[i].keyCount == m - 1) {
splitChild(node, i, node.children[i]);
if (key > node.keys[i]) {
i++;
}
}
insertNonFull(node.children[i], key);
}
}

private void splitChild(BTreeNode parent, int i, BTreeNode child) {


int mid = (m - 1) / 2; // Middle index
BTreeNode newNode = new BTreeNode(m, child.isLeaf);

System.arraycopy(child.keys, mid + 1, newNode.keys, 0, child.keyCount - mid - 1);


if (!child.isLeaf) {
System.arraycopy(child.children, mid + 1, newNode.children, 0, child.keyCount - mid);
}

newNode.keyCount = child.keyCount - mid - 1;


child.keyCount = mid;

for (int j = parent.keyCount; j > i; j--) {


parent.keys[j] = parent.keys[j - 1];
parent.children[j + 1] = parent.children[j];
}
parent.keys[i] = child.keys[mid];
parent.children[i + 1] = newNode;
parent.keyCount++;
}

public boolean search(int key) {


return search(root, key);
}

private boolean search(BTreeNode node, int key) {


int i = 0;
while (i < node.keyCount && key > node.keys[i]) {
i++;
}
if (i < node.keyCount && key == node.keys[i]) {
return true;
}
return !node.isLeaf && search(node.children[i], key);
}

public void delete(int key) {


delete(root, key);
if (root.keyCount == 0 && !root.isLeaf) {
root = root.children[0];
}
}

private void delete(BTreeNode node, int key) {


int i = 0;
while (i < node.keyCount && key > node.keys[i]) {
i++;
}

if (i < node.keyCount && key == node.keys[i]) {


if (node.isLeaf) { // Case 1: Key is in a leaf node
for (int j = i; j < node.keyCount - 1; j++) {
node.keys[j] = node.keys[j + 1];
}
node.keyCount--;
} else { // Case 2: Key is in an internal node
node.keys[i] = getPredecessor(node.children[i]);
delete(node.children[i], node.keys[i]);
}
} else if (!node.isLeaf) {
delete(node.children[i], key);
}
}

private int getPredecessor(BTreeNode node) {


while (!node.isLeaf) {
node = node.children[node.keyCount];
}
return node.keys[node.keyCount - 1];
}

public void display() {


display(root, 0);
}

private void display(BTreeNode node, int level) {


if (node == null) return;
System.out.print("Level " + level + ": ");
for (int i = 0; i < node.keyCount; i++) {
System.out.print(node.keys[i] + " ");
}
System.out.println();

for (int i = 0; i <= node.keyCount; i++) {


display(node.children[i], level + 1);
}
}
}

public class MWAYBTree {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Get M value
int m;
while (true) {
System.out.print("Enter the value of m (3, 5, or 7): ");
m = scanner.nextInt();
if (m == 3 || m == 5 || m == 7) break;
System.out.println("Invalid input! Please enter 3, 5, or 7.");
}

BTree bTree = new BTree(m);


scanner.nextLine(); // Consume newline

// Insert space-separated integers


System.out.print("Enter space-separated integers to insert: ");
String input = scanner.nextLine();
String[] numbers = input.split(" ");

for (String num : numbers) {


bTree.insert(Integer.parseInt(num));
}

while (true) {
System.out.println("\n1. Insert\n2. Delete\n3. Search\n4. Display\n5. Exit");
System.out.print("Choose an operation: ");
int choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.print("Enter key to insert: ");
int key = scanner.nextInt();
bTree.insert(key);
break;
case 2:
System.out.print("Enter key to delete: ");
key = scanner.nextInt();
bTree.delete(key);
break;
case 3:
System.out.print("Enter key to search: ");
key = scanner.nextInt();
System.out.println(bTree.search(key) ? "Key found." : "Key not found.");
break;
case 4:
System.out.println("B-tree structure:");
bTree.display();
break;
case 5:
System.out.println("Exiting.");
scanner.close();
return;
default:
System.out.println("Invalid choice! Try again.");
}
}
}
}
Output:
Enter the value of m (3, 5, or 7): 3
Enter space-separated integers to insert: 10 20 30 40 50

1. Insert
2. Delete
3. Search
4. Display
5. Exit
Choose an operation: 4
B-tree structure:
Level 0: 20 40
Level 1: 10
Level 1: 30
Level 1: 50

1. Insert
2. Delete
3. Search
4. Display
5. Exit
Choose an operation: 3
Enter key to search: 30
Key found.

1. Insert
2. Delete
3. Search
4. Display
5. Exit
Choose an operation: 2
Enter key to delete: 10

1. Insert
2. Delete
3. Search
4. Display
5. Exit
Choose an operation: 4
B-tree structure:
Level 0: 20 40
Level 1:
Level 1: 30
Level 1: 50
Knuth-Morris-Prath
import java.util.*;

public class KMPStringMatching {

// Function to compute LPS (Longest Prefix Suffix) array


private static void computeLPSArray(String pattern, int M, int[] lps) {
int len = 0;
int i = 1;
lps[0] = 0; // First value is always 0

while (i < M) {
if (pattern.charAt(i) == pattern.charAt(len)) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}

// KMP Pattern Searching Algorithm


public static void KMPSearch(String text, String pattern) {
int N = text.length();
int M = pattern.length();
int[] lps = new int[M];

// Preprocess the pattern


computeLPSArray(pattern, M, lps);

int i = 0, j = 0; // i for text, j for pattern


while (i < N) {
if (pattern.charAt(j) == text.charAt(i)) {
i++;
j++;
}
if (j == M) {
System.out.println("Pattern found at index " + (i - j));
j = lps[j - 1];
} else if (i < N && pattern.charAt(j) != text.charAt(i)) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the text: ");
String text = scanner.nextLine();
System.out.print("Enter the pattern to search: ");
String pattern = scanner.nextLine();
scanner.close();

KMPSearch(text, pattern);
}
}

Output:
Enter the text: ABCDEFGHIJ
Enter the pattern to search: EFGHI
Pattern found at index 4
Boyer-Moore
import java.util.*;

public class BoyerMooreStringMatching {


private static final int ALPHABET_SIZE = 256;

// Function to preprocess the bad character heuristic


private static void badCharHeuristic(String pattern, int m, int[] badChar) {
Arrays.fill(badChar, -1);
for (int i = 0; i < m; i++) {
badChar[pattern.charAt(i)] = i;
}
}

// Boyer-Moore Pattern Searching Algorithm


public static void search(String text, String pattern) {
int n = text.length();
int m = pattern.length();
int[] badChar = new int[ALPHABET_SIZE];

// Preprocess the pattern


badCharHeuristic(pattern, m, badChar);

int shift = 0; // Shift of the pattern relative to text


while (shift <= (n - m)) {
int j = m - 1;

while (j >= 0 && pattern.charAt(j) == text.charAt(shift + j)) {


j--;
}

if (j < 0) {
System.out.println("Pattern found at index " + shift);
shift += (shift + m < n) ? m - badChar[text.charAt(shift + m)] : 1;
} else {
shift += Math.max(1, j - badChar[text.charAt(shift + j)]);
}
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the text: ");
String text = scanner.nextLine();
System.out.print("Enter the pattern to search: ");
String pattern = scanner.nextLine();
scanner.close();
search(text, pattern);
}
}

Output:
Enter the text: ABCDABCDABCD
Enter the pattern to search: ABCD
Pattern found at index 0
Pattern found at index 4
Pattern found at index 8

You might also like