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

ADS lab programs

The document contains multiple Java implementations of data structures and algorithms, including Binary Search Tree (BST), Merge Sort, Heap Sort, Quick Sort, AVL Tree, a Hash Dictionary, and the Knuth-Morris-Pratt (KMP) string matching algorithm. Each section includes class definitions, methods for insertion, sorting, and traversal, as well as user interaction through a console menu. The code is structured to allow users to input data and see results for various operations on these data structures.

Uploaded by

P. Sanjay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views18 pages

ADS lab programs

The document contains multiple Java implementations of data structures and algorithms, including Binary Search Tree (BST), Merge Sort, Heap Sort, Quick Sort, AVL Tree, a Hash Dictionary, and the Knuth-Morris-Pratt (KMP) string matching algorithm. Each section includes class definitions, methods for insertion, sorting, and traversal, as well as user interaction through a console menu. The code is structured to allow users to input data and see results for various operations on these data structures.

Uploaded by

P. Sanjay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 18

// Bst

import java.util.Scanner;

// Node class representing a node in the BST


class Node {
int data;
Node left, right;

public Node(int data) {


this.data = data;
this.left = this.right = null;
}
}

// BST class containing methods for insertion, in-order traversal, and the main function
class BST {
static Node root=null;

// Helper method for insertion (recursive)


public Node insert(Node root, int data) {
if (root == null) {
root = new Node(data);
return root;
}

if (data < root.data) {


root.left = insert(root.left, data);
} else if (data > root.data) {
root.right = insert(root.right, data);
}

return root;
}

// Helper method for in-order traversal (recursive)


public void inOrder(Node root) {
if (root != null) {
inOrder(root.left);
System.out.print(root.data + " ");
inOrder(root.right);
}
}

// Main function with menu


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

System.out.println("\nMenu:");
System.out.println("1. Insert a node");
System.out.println("2. Display in-order traversal");
System.out.println("3. Exit");

while (true) {
System.out.print("Enter your choice: ");

int choice = scanner.nextInt();


switch (choice) {
case 1:
System.out.print("Enter the number of elements to insert: ");
int n = scanner.nextInt();
for(int i=0;i<n;i++){
System.out.print("Enter value to insert: ");
int value = scanner.nextInt();

root = bst.insert(root, value);


System.out.println("Value inserted successfully.");
}
break;

case 2:
System.out.println("In-order traversal:");
bst.inOrder(root);
System.out.println(); // For better formatting
break;

case 3:
System.out.println("Exiting program. Goodbye!");
scanner.close();
System.exit(0);
break;

default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}

// merge sort

import java.util.Scanner;

public class MergeSortSimple {

// Merge Sort function


public static void mergeSort(int[] arr, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;

// Recursively sort left and right halves


mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);

// Merge sorted halves


merge(arr, left, mid, right);
}
}

// Merge function
public static void merge(int[] arr, int left, int mid, int right) {
int[] temp = new int[right - left + 1];
int i = left, j = mid + 1, k = 0;

while (i <= mid && j <= right) {


temp[k++] = (arr[i] <= arr[j]) ? arr[i++] : arr[j++];
}

while (i <= mid) temp[k++] = arr[i++];


while (j <= right) temp[k++] = arr[j++];

// Copy sorted elements back to original array


for (i = left, k = 0; i <= right; i++, k++) {
arr[i] = temp[k];
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter number of elements: ");


int n = scanner.nextInt();

int[] arr = new int[n];


System.out.println("Enter the elements:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

mergeSort(arr, 0, n - 1);

System.out.println("Sorted array:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}

// heap sort

import java.util.Scanner;

public class HeapSort {

// Function to perform heap sort


public static void heapSort(int[] arr) {
int n = arr.length;

// Build a max heap


for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}

// Extract elements from heap one by one


for (int i = n - 1; i > 0; i--) {
// Move the current root to the end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;

// Call heapify on the reduced heap


heapify(arr, i, 0);
}
}

// Function to heapify a subtree rooted at index i


public static void heapify(int[] arr, int n, int i) {
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // left = 2*i + 1
int right = 2 * i + 2; // right = 2*i + 2

// If left child is larger than root


if (left < n && arr[left] > arr[largest]) {
largest = left;
}

// If right child is larger than largest so far


if (right < n && arr[right] > arr[largest]) {
largest = right;
}

// If largest is not root


if (largest != i) {
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;

// Recursively heapify the affected subtree


heapify(arr, n, largest);
}
}

// Function to print the array


public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}

// Main function to take user input and test heap sort


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Taking user input for the size of the array
System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();

// Creating the array and taking user input for its elements
int[] arr = new int[n];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

System.out.println("Unsorted array:");
printArray(arr);

heapSort(arr);

System.out.println("Sorted array:");
printArray(arr);

scanner.close();
}
}

// quick sort

import java.util.Scanner;

class QuickSort {
void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pivot = partition(arr, low, high);
quickSort(arr, low, pivot - 1); // Left of pivot
quickSort(arr, pivot + 1, high); // Right of pivot
}
}

int partition(int[] arr, int low, int high) {


int pivot = arr[high], i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
arr[high] = arr[i + 1];
arr[i + 1] = pivot;
return i + 1;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
QuickSort sorter = new QuickSort();

System.out.println("Enter number of elements:");


int n = sc.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}

sorter.quickSort(arr, 0, n - 1);

System.out.println("Sorted array:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}

// Avl

import java.util.Scanner;

class AVLTree {
class Node {
int key, height;
Node left, right;

Node(int d) {
key = d;
height = 1;
}
}

Node root;

int height(Node n) {
if (n == null) {
return 0;
}
return n.height;
}

int balanceFactor(Node n) {
if (n == null) {
return 0;
}
return height(n.left) - height(n.right);
}
Node rotateRight(Node y) {
Node x = y.left;
Node T = x.right;
x.right = y;
y.left = T;
y.height = Math.max(height(y.left), height(y.right)) + 1;
x.height = Math.max(height(x.left), height(x.right)) + 1;
return x;
}

Node rotateLeft(Node x) {
Node y = x.right;
Node T = y.left;
y.left = x;
x.right = T;
x.height = Math.max(height(x.left), height(x.right)) + 1;
y.height = Math.max(height(y.left), height(y.right)) + 1;
return y;
}

Node insert(Node node, int key) {


if (node == null) {
return new Node(key);
}

if (key < node.key) {


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

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


int balance = balanceFactor(node);

if (balance > 1 && key < node.left.key) {


return rotateRight(node); // Left-Left case
}

if (balance < -1 && key > node.right.key) {


return rotateLeft(node); // Right-Right case
}

if (balance > 1 && key > node.left.key) {


node.left = rotateLeft(node.left); // Left-Right case
return rotateRight(node);
}

if (balance < -1 && key < node.right.key) {


node.right = rotateRight(node.right); // Right-Left case
return rotateLeft(node);
}

return node;
}

void inOrder(Node node) {


if (node != null) {
inOrder(node.left);
System.out.print(node.key + " ");
inOrder(node.right);
}
}

public static void main(String[] args) {


AVLTree tree = new AVLTree();
Scanner sc = new Scanner(System.in);

System.out.println("Enter numbers to insert (-1 to stop):");


while (true) {
int num = sc.nextInt();
if (num == -1) {
break;
}
tree.root = tree.insert(tree.root, num);
}
sc.close();

System.out.println("In-order traversal of AVL tree:");


tree.inOrder(tree.root);
}
}

// dictionary

import java.util.Scanner;

class HashDictionary {
private String[] words; // Array to store words
private String[] meanings; // Array to store meanings of words
private int size; // Size of the dictionary (capacity)
private int count; // Number of words currently in the dictionary

// Constructor to initialize the dictionary with a given capacity


public HashDictionary(int capacity) {
size = capacity;
words = new String[size];
meanings = new String[size];
count = 0;
}

// Hash function to generate a hash value for the word (based on character values)
private int hashFunction(String key) {
return key.chars().sum() % size; // Sum of character codes mod size
}
// Insert a word with its meaning into the dictionary
public void insert(String word, String meaning) {
if (count == size) {
System.out.println("Dictionary is full. Cannot insert new words.");
return;
}

int index = hashFunction(word); // Get hash index for the word

// Linear probing: if the slot is occupied, find the next available slot
while (words[index] != null) {
if (words[index].equals(word)) {
meanings[index] = meaning; // Update meaning if word already exists
System.out.println("Updated: " + word);
return;
}
index = (index + 1) % size; // Move to next index
}

// Insert the new word and meaning in the available slot


words[index] = word;
meanings[index] = meaning;
count++;
System.out.println("Inserted: " + word);
}

// Display all the words and their meanings in alphabetical order


public void display() {
String[][] entries = new String[count][2]; // Temporary array to store entries
int idx = 0;

// Collect all words and their meanings in the temporary array


for (int i = 0; i < size; i++) {
if (words[i] != null) {
entries[idx++] = new String[]{words[i], meanings[i]};
}
}

// Sort the entries alphabetically by word


java.util.Arrays.sort(entries, (a, b) -> a[0].compareTo(b[0]));

// Print the sorted dictionary


for (String[] entry : entries) {
System.out.println(entry[0] + " -> " + entry[1]);
}
}

// Search for a word and display its meaning


public void search(String word) {
int index = hashFunction(word); // Get hash index for the word
int start = index; // Store the starting index to detect when we circle back

// Search using linear probing until the word is found or the dictionary is fully searched
while (words[index] != null) {
if (words[index].equals(word)) {
System.out.println(word + " -> " + meanings[index]);
return;
}
index = (index + 1) % size; // Move to next index
if (index == start) break; // Prevent infinite loop if all slots are searched
}
System.out.println("Word not found.");
}

// Main method to interact with the user


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter dictionary capacity: ");
int capacity = scanner.nextInt(); // Get dictionary capacity from user
scanner.nextLine(); // Consume the newline character after integer input

HashDictionary dict = new HashDictionary(capacity); // Create a dictionary with the specified


capacity

while (true) {
// Menu options for the user
System.out.println("\n1. Insert\n2. Display\n3. Search\n4. Exit");
int choice = scanner.nextInt(); // Get the user’s choice
scanner.nextLine(); // Consume the newline character after integer input

switch (choice) {
case 1:
System.out.print("Word: ");
String word = scanner.nextLine(); // Get the word to insert
System.out.print("Meaning: ");
String meaning = scanner.nextLine(); // Get the meaning of the word
dict.insert(word, meaning); // Insert the word and its meaning into the dictionary
break;
case 2:
dict.display(); // Display all the words in the dictionary
break;
case 3:
System.out.print("Search word: ");
word = scanner.nextLine(); // Get the word to search
dict.search(word); // Search for the word in the dictionary
break;
case 4:
scanner.close(); // Close the scanner and exit the program
return;
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}
// kmp

import java.util.Scanner;

class KMP {
static void constructLps(String pat, int[] lps) {
int len = 0;
lps[0] = 0;
int i = 1;
while (i < pat.length()) {
if (pat.charAt(i) == pat.charAt(len)) {
len++;
lps[i] = len;
i++;
}
else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}

static int[] search(String pat, String txt) {


int n = txt.length();
int m = pat.length();
int[] lps = new int[m];
int[] res = new int[n];
int count = 0;
constructLps(pat, lps);
int i = 0;
int j = 0;
while (i < n) {
if (txt.charAt(i) == pat.charAt(j)) {
i++;
j++;
if (j == m) {
res[count] = i - j;
count++;
j = lps[j - 1];
}
}
else {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
int[] finalRes = new int[count];
for (int k = 0; k < count; k++) {
finalRes[k] = res[k];
}
return finalRes;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the text: ");
String txt = scanner.nextLine();
System.out.print("Enter the pattern to search: ");
String pat = scanner.nextLine();
int[] res = search(pat, txt);
if (res.length == 0) {
System.out.println("Pattern not found in the text.");
} else {
System.out.println("Pattern found at the following indices:");
for (int i = 0; i < res.length; i++) {
System.out.println("text found at "+res[i] );
}
System.out.println();
}

scanner.close();
}
}

// brute force

import java.util.Scanner;

public class BruteForce {

// Function to implement Brute Force Pattern Matching


public static void bruteForcePatternSearch(String text, String pattern) {
int n = text.length();
int m = pattern.length();

// Edge case: if pattern is longer than text, no match is possible


if (m > n) {
System.out.println("Pattern is longer than the text. No matches found.");
return;
}

// Loop to iterate over the text


for (int i = 0; i <= n - m; i++) {
int j = 0;

// Check if the pattern matches at the current position in the text


while (j < m && text.charAt(i + j) == pattern.charAt(j)) {
j++;
}

// If we have found a match, print the index


if (j == m) {
System.out.println("Pattern found at index " + i);
}
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Take user inputs for the text and pattern


System.out.print("Enter the text: ");
String text = scanner.nextLine();

System.out.print("Enter the pattern: ");


String pattern = scanner.nextLine();

// Edge case: empty text or pattern


if (text.isEmpty() || pattern.isEmpty()) {
System.out.println("Text or pattern cannot be empty.");
} else {
// Call the brute force pattern search method
bruteForcePatternSearch(text, pattern);
}

scanner.close();
}
}

// boyer

import java.util.Scanner;

public class Boyer {

// Function to build the bad character table


public static int[] buildBadCharTable(String pattern) {
int[] badChar = new int[256]; // For all ASCII characters

// Initialize the bad character table with -1 (not found)


for (int i = 0; i < 256; i++) {
badChar[i] = -1;
}

// Fill the bad character table with the index of each character in the pattern
for (int i = 0; i < pattern.length(); i++) {
badChar[pattern.charAt(i)] = i;
}

return badChar;
}

// Boyer-Moore Pattern Matching


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

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


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

// Compare the pattern from right to left with the text


while (j >= 0 && pattern.charAt(j) == text.charAt(s + j)) {
j--;
}

// If the pattern matches


if (j < 0) {
System.out.println("Pattern found at index " + s);
// Move the pattern to the next position after the match
if (s + m < n) {
s += m - badChar[text.charAt(s + m)];
} else {
s++;
}
} else {
// Move the pattern based on the bad character heuristic
s += Math.max(1, j - badChar[text.charAt(s + j)]);
}
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Take user inputs for the text and pattern


System.out.print("Enter the text: ");
String text = scanner.nextLine();

System.out.print("Enter the pattern: ");


String pattern = scanner.nextLine();

// Call the Boyer-Moore pattern search method


boyerMooreSearch(text, pattern);

scanner.close();
}
}
// shortest path

import java.util.Scanner;

public class Short {

// Function to find the vertex with the minimum distance value that is not yet processed
private static int minDistance(int[] dist, boolean[] sptSet, int vertices) {
int min = Integer.MAX_VALUE;
int minIndex = -1;

for (int v = 0; v < vertices; v++) {


if (sptSet[v] == false && dist[v] <= min) {
min = dist[v];
minIndex = v;
}
}
return minIndex;
}

// Function to implement Dijkstra’s algorithm and print the shortest path


public static void dijkstra(int[][] graph, int src, int dest, int vertices) {
int[] dist = new int[vertices]; // Array to store the shortest distance from the source to each vertex
boolean[] sptSet = new boolean[vertices]; // Boolean array to track the vertices included in the
shortest path tree
int[] parent = new int[vertices]; // Array to store the path

// Initialize all distances as INFINITE and sptSet[] as false


for (int i = 0; i < vertices; i++) {
dist[i] = Integer.MAX_VALUE;
sptSet[i] = false;
parent[i] = -1; // Initialize parent to -1 (no parent)
}

// Distance from source to itself is always 0


dist[src] = 0;

// Find the shortest path for all vertices


for (int count = 0; count < vertices - 1; count++) {
int u = minDistance(dist, sptSet, vertices);
sptSet[u] = true;

// Update the distance values of the adjacent vertices of the selected vertex
for (int v = 0; v < vertices; v++) {
if (!sptSet[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] <
dist[v]) {
dist[v] = dist[u] + graph[u][v];
parent[v] = u; // Set parent of v to u
}
}
}
// Print the shortest path and the total weight
if (dist[dest] == Integer.MAX_VALUE) {
System.out.println("No path exists from source to destination.");
} else {
System.out.println("Shortest path from " + src + " to " + dest + ": ");
printPath(parent, dest);
System.out.println("\nTotal weight: " + dist[dest]);
}
}

// Helper function to print the path from source to destination


private static void printPath(int[] parent, int j) {
if (parent[j] == -1) {
System.out.print(j);
return;
}
printPath(parent, parent[j]);
System.out.print(" -> " + j);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Taking user input for number of vertices and edges


System.out.print("Enter the number of vertices: ");
int vertices = scanner.nextInt();

int[][] graph = new int[vertices][vertices];

System.out.print("Enter the number of edges: ");


int edges = scanner.nextInt();

// Taking user input for the edges and their weights (source, destination, weight)
for (int i = 0; i < edges; i++) {
System.out.print("Enter the edge " + (i + 1) + " (format: source destination weight): ");
int start = scanner.nextInt();
int end = scanner.nextInt();
int weight = scanner.nextInt();

// Since it’s an undirected graph, we add the weight in both directions


graph[start][end] = weight;
graph[end][start] = weight;
}

// Taking user input for the source and destination vertex


System.out.print("Enter the source vertex: ");
int source = scanner.nextInt();

System.out.print("Enter the destination vertex: ");


int destination = scanner.nextInt();

// Calling Dijkstra’s algorithm


dijkstra(graph, source, destination, vertices);

scanner.close();
}
}

// graph ( bfs and dfs)


import java.util.Scanner;

class Graph {
private int[][] adjMatrix;
private boolean[] visited;
private int size;

public Graph(int size) {


this.size = size;
adjMatrix = new int[size][size];
visited = new boolean[size];
}

void addEdge(int u, int v) {


if (u >= 0 && u < size && v >= 0 && v < size) {
adjMatrix[u][v] = adjMatrix[v][u] = 1;
}
}

void dfs(int node) {


visited[node] = true;
System.out.print(node + " ");
for (int i = 0; i < size; i++) {
if (adjMatrix[node][i] == 1 && !visited[i]) {
dfs(i);
}
}
}

void bfs(int start) {


boolean[] visited = new boolean[size];
int[] queue = new int[size];
int front = 0, rear = 0;

visited[start] = true;
queue[rear++] = start;

while (front < rear) {


int node = queue[front++];
System.out.print(node + " ");

for (int i = 0; i < size; i++) {


if (adjMatrix[node][i] == 1 && !visited[i]) {
visited[i] = true;
queue[rear++] = i;
}
}
}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

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


Graph graph = new Graph(sc.nextInt());

System.out.println("Enter number of edges:");


int edges = sc.nextInt();
System.out.println("Enter edges (u v):");
for (int i = 0; i < edges; i++) {
graph.addEdge(sc.nextInt(), sc.nextInt());
}

System.out.println("Enter starting node for traversal:");


int startNode = sc.nextInt();

System.out.println("DFS Traversal:");
graph.visited = new boolean[graph.size]; // Reset visited array
graph.dfs(startNode);

System.out.println("\nBFS Traversal:");
graph.bfs(startNode);

sc.close();
}
}

You might also like