0% found this document useful (0 votes)
26 views41 pages

DS Practical ZIBRAN

Zibran

Uploaded by

mdzibran010
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views41 pages

DS Practical ZIBRAN

Zibran

Uploaded by

mdzibran010
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Plot No.

2, Sector 17-A Yamuna Expressway, Opposite Buddha International


Circuit, Greater Noida, Gautam Buddh Nagar, Uttar Pradesh 203201

SUBJECT NAME : DATA STRUCTURE PRACTICAL

SUBJECT CODE: E2UC303B

FACULTY NAME: MR. K. RAJKANNAN

SUBMITTED BY:-

NAME: MD ZIBRAN ALI

ADMISSION NUMBER: 22SCSE1010859

SECTION: 19

SEMESTER: III
1 Write a program to reverse an array without using an additional array.

Ans:

Algorithm:-

1. Input Size:

• Read the size of the array from the user.

2. Array Input:

• Create an array of integers with the specified size.

• Read the elements of the array from the user.

3. Reverse Array Algorithm (reverseArray method):

• Initialize two pointers: startIndex pointing to the first element of


the array, and endIndex pointing to the last element of the array.

• Use a while loop to iterate until startIndex is less than endIndex.

• Swap the values at positions startIndex and endIndex.

• Move startIndex one position forward and endIndex one position


backward.

4. Print Reversed Array:

• Print the reversed array by iterating through it and displaying each


element.

Program:-

import java.util.Scanner;

public class ArrayReverser {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter the size of the array:");

int size = scanner.nextInt();

int[] array = new int[size];

System.out.println("Enter " + size + " elements:");

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

array[i] = scanner.nextInt();

reverseArray(array);
System.out.println("Reversed array:");

for (int num : array) {

System.out.print(num + " ");

public static void reverseArray(int[] array) {

int startIndex = 0;

int endIndex = array.length - 1;

while (startIndex < endIndex) {

// Swap the values

int temp = array[startIndex];

array[startIndex] = array[endIndex];

array[endIndex] = temp;

// Move indices towards the center

startIndex++;

endIndex--;

Output:

Enter the size of the array:

Enter 5 elements:

12345

Reversed array:

54321
Time and Space Complexity:-

• Time Complexity: O(n)

• Space Complexity: O(1)

2 Write a program to find second largest element in an array of integers.

Ans:

Algorithm:-

1. Function print2largest:

• Input: Integer array arr, integer arr_size (size of the array).

• Sort the array arr in descending order using Arrays.sort with


Collections.reverseOrder().

• Iterate over the sorted array from index 1 to arr_size - 1:

• If the current element (arr[i]) is different from the first


element (arr[0]), print it as the second largest element and
return.

• If the loop completes without finding a second largest element, print


that there is no second largest element.

2. Main Function:

• Create an Integer array arr with values {12, 35, 1, 10, 34, 1}.

• Get the length of the array n.

• Call the print2largest function with the array arr and its length n.

3. End of Algorithm.

Program:-

import java.util.*;

class GFG {

static void print2largest(Integer arr[], int arr_size){

Arrays.sort(arr, Collections.reverseOrder());

for (int i = 1; i < arr_size; i++) {

if (arr[i] != arr[0]) {

System.out.printf("The second largest "

+ "element is %d\n", arr[i]);

return;
}

System.out.printf("There is no second "+ "largest element\n");

public static void main(String[] args)

Integer arr[] = { 12, 35, 1, 10, 34, 1 };

int n = arr.length;

print2largest(arr, n);

Output:

The second largest element is 34

Time and Space Complexity:-

• Time Complexity: O(n log n)

• Space Complexity: O(n)

3 Write a program to implement linked list by adding or removing element at


given position.

Ans:

Algorithm:-

1. Initialize Linked List:

• Create a class LinkedList with a nested class Node to represent


nodes in the linked list.

• Initialize a variable head as the starting node of the list.

2. Node Class:

• Create a class Node with data and a reference to the next node.

3. Push Operation (push method):

• Input: new_data - data for the new node.


• Create a new node with the given data.

• Set the next of the new node to the current head.

• Update head to the new node.

4. Delete Node Operation (deleteNode method):

• Input: position - position of the node to be deleted (0-based


index).

• If the list is empty (head is null), return.

• If position is 0, update head to the next node and return.

• Traverse the list to the node before the one to be deleted.

• Update the next reference of the previous node to skip the node
to be deleted.

5. Print List Operation (printList method):

• Traverse the linked list from head to the end, printing each
node's data.

6. Main Function:

• Create a new linked list (llist).

• Push elements 7, 1, 3, 2, and 8 onto the linked list.

• Print the initial state of the linked list.

• Delete the node at position 4.

• Print the linked list after the deletion.

Program:-

import java.io.*;

class LinkedList {

Node head;

class Node {

int data;

Node next;

Node(int d)

data = d;

next = null;
}

public void push(int new_data)

Node new_node = new Node(new_data);

new_node.next = head;

head = new_node;

void deleteNode(int position)

if (head == null)

return;

Node temp = head;

if (position == 0) {

head = temp.next;

return;

for (int i = 0; temp != null && i < position - 1;

i++)

temp = temp.next;

if (temp == null || temp.next == null)

return;

Node next = temp.next.next;

temp.next= next;

public void printList()

Node tnode = head;

while (tnode != null) {

System.out.print(tnode.data + " ");

tnode = tnode.next;
}

public static void main(String[] args){

LinkedList llist = new LinkedList();

llist.push(7);

llist.push(1);

llist.push(3);

llist.push(2);

llist.push(8);

System.out.println("\nCreated Linked list is: ");

llist.printList();

llist.deleteNode(4); // Delete node at position 4

System.out.println(

"\nLinked List after Deletion at position 4: ");

llist.printList();

Output:

Created Linked List: 8 2 3 1 7

Linked List after Deletion at position 4: 8 2 3 1

Time and Space Complexity:-

• Time Complexity: O(n)

• Space Complexity: O(n)

4 Write a program to find second smallest element in a linked list.

Ans:

Algorithm:-

1. Define Node Class:


• Create a class Node with public integer data (data) and a
reference to the next node (next).

2. Main Class (Main):

• Create a static method findSecondSmallest that takes the head of


the linked list as a parameter and returns the second smallest
element.

• If the linked list is empty or has only one node, return


Integer.MAX_VALUE as there is no second smallest
element.

• Initialize an array arr with the data of the first two nodes
and sort it.

• Iterate through the remaining nodes, updating the array


with the two smallest elements.

• Return the second smallest element (arr[1]).

3. Main Function:

• In the main function:

• Create a linked list with sample data.

• Call the findSecondSmallest method to get the second


smallest element.

• Print the result.

Program:-
import java.util.Arrays;

class Node {

public int data;

public Node next;

class Main {

public static int findSecondSmallest(Node head)

if (head == null || head.next == null) {

return Integer.MAX_VALUE;

int[] arr = { head.data, head.next.data };


Arrays.sort(arr);

Node curr = head.next.next;

while (curr != null) {

if (curr.data < arr[0]) {

arr[1] = arr[0];

arr[0] = curr.data;

else if (curr.data < arr[1]

&& curr.data != arr[0]) {

arr[1] = curr.data;

curr = curr.next;

return arr[1];

public static void main(String[] args)

// Create a linked list

Node head = new Node();

head.data = 1;

head.next = new Node();

head.next.data = 34;

head.next.next = new Node();

head.next.next.data = 10;

head.next.next.next = new Node();

head.next.next.next.data = 1;

head.next.next.next.next = new Node();

head.next.next.next.next.data = 35;

head.next.next.next.next.next = new Node();

head.next.next.next.next.next.data = 12;

int secondSmallest = findSecondSmallest(head);

if (secondSmallest == Integer.MAX_VALUE) {
System.out.println(

"There is no second smallest element in the list.");

else {

System.out.println(

"The second smallest element in the list is "

+ secondSmallest + ".");

Output:
The second smallest element in the list is 10.

Time and Space Complexity:-

• Time Complexity: O(n)

• Space Complexity: O(1)

5 Write a recursive program to find the nth Fibonacci number.

Ans:

Algorithm:-
1. Define Function fib:

• Input: Integer n representing the position of the desired Fibonacci number.

• Initialize variables a and b to 0 and 1, respectively.

• If n is 0, return a.

• Iterate from 2 to n (inclusive):

• Calculate the next Fibonacci number c as the sum of a and b.

• Update a to the current value of b.

• Update b to the current value of c.

• Return the value of b as the nth Fibonacci number.

2. Main Function:

• Set the value of n to 9 (or any desired position).


• Call the fib function with n as an argument.

• Print the result.

Program:-
public class fibonacci {

static int fib(int n)

int a = 0, b = 1, c;

if (n == 0)

return a;

for (int i = 2; i <= n; i++) {

c = a + b;

a = b;

b = c;

return b;

public static void main(String args[])

int n = 9;

System.out.println(fib(n));

};

Output:
34

Time and Space Complexity:-

• Time Complexity: O(n)

• Space Complexity: O(1)

6 Write a program to solve the TOH problem.

Ans:

Algorithm:-
1. Define Function towerOfHanoi:

• Input:

• Integer n: Number of disks to be moved.

• Characters from_rod, to_rod, aux_rod: Names of the source


rod, destination rod, and auxiliary rod.

• Base Case:

• If n is 1, print the move of disk 1 from the source rod to the


destination rod, and return.

• Recursive Steps:

• Move n-1 disks from the source rod to the auxiliary rod
using the destination rod as an auxiliary.

• Print the move of disk n from the source rod to the


destination rod.

• Move the n-1 disks from the auxiliary rod to the


destination rod using the source rod as an auxiliary.

2. Main Function:

• Set the value of n to 4 (or any desired number of disks).

• Call the towerOfHanoi function with the source rod as 'A',


destination rod as 'C', and auxiliary rod as 'B'.

• The function will print the sequence of moves to solve the Tower
of Hanoi problem.

Program:-
class GFG {

static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) {

if (n == 1) {

System.out.println("Move disk 1 from rod " + from_rod + " to rod " + to_rod);

return;

towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);

System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod);

towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);

public static void main(String args[])

{
int n = 4; // Number of disks

towerOfHanoi(n, \'A\', \'C\', \'B\'); // A, B and C are names of rods

Output:
Move disk 1 from rod A to rod B

Move disk 2 from rod A to rod C

Move disk 1 from rod B to rod C

Move disk 3 from rod A to rod B

Move disk 1 from rod C to rod A

Move disk 2 from rod C to rod B

Move disk 1 from rod A to rod B

Move disk 4 from rod A to rod C

Move disk 1 from rod B to rod C

Move disk 2 from rod B to rod A

Move disk 1 from rod C to rod A

Move disk 3 from rod B to rod C

Move disk 1 from rod A to rod B

Move disk 2 from rod A to rod C

Move disk 1 from rod B to rod C

Time and Space Complexity:-

• Time Complexity: O(2^n)

• Space Complexity: O(n)

7 Write a program to find the largest number in the stack.

Ans:

Algorithm:-

1. Define Function sortStack:

• Input: Stack of integers (input).

• Output: Stack of integers sorted in ascending order.


• Create an auxiliary stack (sortedStack) to store sorted elements.

• While the input stack is not empty:

• Pop the top element (current) from the input stack.

• While the sorted stack is not empty and the top of the
sorted stack is greater than current:

• Pop elements from the sorted stack and push them


back to the input stack.

• Push current onto the sorted stack.

• Return the sorted stack.

2. Define Function findKthLargestNum:

• Input: Stack of integers sorted in ascending order (sortedStack),


integer k.

• Print the kth largest element from the top of the sorted stack.

3. Main Function:

• Initialize an empty stack (inputStack).

• Read the number of elements n from the user.

• Read n integers from the user and push them onto the input
stack.

• If the input stack is empty, print "stack is empty" and exit.

• Read the value of k from the user.

• If k is greater than the size of the input stack, print "invalid


input" and exit.

• Create a temporary stack (temp) by sorting the input stack using


the sortStack function.

• Find and print the kth largest element from the sorted stack
using the findKthLargestNum function.

Program:-

import java.util.*;

public class Source {

public static Stack < Integer > sortStack(Stack < Integer > input) {

public static void findKthLargestNum(Stack <Integer> sortedStack, int k) {


}

public static void main(String args[]) {

Stack < Integer > inputStack = new Stack < Integer > ();

Scanner in = new Scanner(System.in);

int n = in .nextInt();

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

inputStack.add( in .nextInt());

if (inputStack.isEmpty()) {

System.out.println("stack is empty");

System.exit(0);

int k = in .nextInt();

if (k > inputStack.size()) {

System.out.println("invalid input");

System.exit(0);

Stack < Integer > temp = sortStack(inputStack);

findKthLargestNum(temp, k);

Time and Space Complexity:-

• Time Complexity: O(n^2)

• Space Complexity: O(n)

8 Write a program to evaluate a postfix expression.

Ans:

Algorithm:-

1. Define Function evaluatePostfix:

• Input: A string exp representing a postfix expression.


• Output: The result of evaluating the postfix expression.

• Create an empty stack (stack) to store operands.

• Iterate through each character c in the postfix expression:

• If c is a digit, convert it to an integer and push it onto the


stack.

• If c is an operator (+, -, *, /):

• Pop the top two values (val1 and val2) from the stack.

• Perform the corresponding operation based on the


operator.

• Push the result back onto the stack.

• After processing the entire expression, the final result is on top of


the stack.

• Pop and return the result.

2. Main Function:

• Initialize a string exp with a sample postfix expression.

• Call the evaluatePostfix function with the postfix expression as an


argument.

• Print the result.

Program:-

import java.util.Stack;

public class Test {

static int evaluatePostfix(String exp)

Stack<Integer> stack = new Stack<>();

for (int i = 0; i < exp.length(); i++) {

char c = exp.charAt(i);

if (Character.isDigit(c))

stack.push(c - '0');

else {

int val1 = stack.pop();

int val2 = stack.pop();

switch (c) {
case '+':

stack.push(val2 + val1);

break;

case '-':

stack.push(val2 - val1);

break;

case '/':

stack.push(val2 / val1);

break;

case '*':

stack.push(val2 * val1);

break;

return stack.pop();

public static void main(String[] args)

String exp = "231*+9-";

System.out.println("postfix evaluation: "

+ evaluatePostfix(exp));

Output:

postfix evaluation: -4

Time and Space Complexity:-

• Time Complexity: O(n)


• Space Complexity: O(n)

9 Write a program to implement Circular Queue using linked list.

Ans:

Algorithm:-

1. Define Class Solution:

• Define a static nested class Node to represent a node in the


linked list with int data and Node link.

• Define a static nested class Queue to represent the circular queue


with Node front and Node rear.

2. Define Functions:

• enQueue(Queue q, int value):

• Input: Circular queue q and an integer value to be


enqueued.

• Create a new node temp with the given value.

• If the queue is empty, set both front and rear to temp.

• Otherwise, link the current rear to temp and update rear to


temp.

• Link rear to front to make the queue circular.

• deQueue(Queue q):

• Input: Circular queue q.

• Check if the queue is empty. If so, print an error message


and return Integer.MIN_VALUE.

• If the queue has only one element, set front and rear to
null.

• Otherwise, update front to the next node and link rear to


the updated front.

• displayQueue(Queue q):

• Input: Circular queue q.

• Iterate through the queue and print each element until the
linked list forms a complete circle.

3. Main Function (main):

• Create a circular queue q.


• Enqueue values 14, 22, and 6.

• Display the queue.

• Dequeue two values and display the queue.

• Enqueue values 9 and 20.

• Display the final queue

Program:-

import java.io.*;

import java.util.*;

public class Solution {

static class Node {

int data;

Node link;

static class Queue {

Node front, rear;

static void enQueue(Queue q, int value)

Node temp = new Node();

temp.data = value;

if (q.front == null)

q.front = temp;

else

q.rear.link = temp;

q.rear = temp;

q.rear.link = q.front;

static int deQueue(Queue q)


{

if (q.front == null) {

System.out.printf("Queue is empty");

return Integer.MIN_VALUE;

int value;

if (q.front == q.rear) {

value = q.front.data;

q.front = null;

q.rear = null;

else

Node temp = q.front;

value = temp.data;

q.front = q.front.link;

q.rear.link = q.front;

return value;

static void displayQueue(Queue q)

Node temp = q.front;

System.out.printf(

"\nElements in Circular Queue are: ");

while (temp.link != q.front) {

System.out.printf("%d ", temp.data);

temp = temp.link;

System.out.printf("%d", temp.data);
}

public static void main(String args[])

Queue q = new Queue();

q.front = q.rear = null;

enQueue(q, 14);

enQueue(q, 22);

enQueue(q, 6);

displayQueue(q);

System.out.printf("\nDeleted value = %d",

deQueue(q));

System.out.printf("\nDeleted value = %d",

deQueue(q));

displayQueue(q);

enQueue(q, 9);

enQueue(q, 20);

displayQueue(q);

Output:

Elements in Circular Queue are: 14 22 6

Deleted value = 14

Deleted value = 22

Elements in Circular Queue are: 6

Elements in Circular Queue are: 6 9 20

Time and Space Complexity:-

• Time Complexity: O(n)

• Space Complexity: O(n)


10 Write a Program to implement Priority Queue using array.

Ans:

Algorithm:-

1. Define Class PriorityQueue:

• Initialize an ArrayList of type Pair to represent the priority


queue.

2. Define Function insert:

• Input: String val - the value to be inserted, int priority - the


priority of the value.

• Create a new Pair with the given value and priority.

• Add the pair to the end of the priority queue.

3. Define Function remove:

• Find the index of the pair with the highest priority.

• Retrieve the value from the pair at the maximum priority index.

• Shift all elements to the left from the right of the maximum
priority index.

• Remove the last element of the priority queue.

• Return the removed value.

4. Define Class Pair:

• A private nested class representing a pair with a String val and


an int priority.

5. Main Function (main):

• Create an instance of PriorityQueue.

• Insert four tasks with different priorities into the priority queue.

• Remove and print the tasks in order of decreasing priority.

Program:-

import java.util.ArrayList;

class PriorityQueue

ArrayList<Pair> queue;
public PriorityQueue() {

this.queue = new ArrayList<Pair>();

public void insert(String val, int priority)

Pair pair = new Pair(val, priority);

this.queue.add(pair);

public String remove() {

int maxIdx = 0;

for (int i = 1; i < this.queue.size(); i++) {

if (this.queue.get(i).priority > this.queue.get(maxIdx).priority) {

maxIdx = i;

String val = this.queue.get(maxIdx).val;

while (maxIdx < this.queue.size() - 1) {

this.queue.set(maxIdx, this.queue.get(maxIdx + 1));

maxIdx++;

this.queue.remove(this.queue.size() - 1);

return val;

private class Pair {

String val;

int priority;

public Pair(String val, int priority) {

this.val = val;

this.priority = priority;

}
public static void main(String[] args) {

PriorityQueue pq = new PriorityQueue();

pq.insert("Task 1", 1);

pq.insert("Task 2", 2);

pq.insert("Task 3", 3);

pq.insert("Task 4", 4);

System.out.println(pq.remove());

System.out.println(pq.remove());

System.out.println(pq.remove());

System.out.println(pq.remove());

Output:

Task 4

Task 3

Task 2

Task 1

Time and Space Complexity:-

• Time Complexity: O(n)

• Space Complexity: O(n)

11 Write a program to search an element in array using binary


search(recursion).

Ans:

Algorithm:-

1. Binary Search Algorithm:

• Input:

• Output:

2. Procedure:
• Check if r is greater than or equal to l (base case).

• Calculate the middle index mid using the formula mid = l + (r - l) /


2.

• If the element at arr[mid] is equal to x, return mid.

• If the element at arr[mid] is greater than x, recursively search in


the left half (l to mid - 1).

• If the element at arr[mid] is less than x, recursively search in the


right half (mid + 1 to r).

• If none of the above conditions match, return -1 (element not


found).

3. Main Function (main):

• Create an instance of the GFG class.

• Define a sorted array arr.

• Specify the length of the array n.

• Set the element to be searched x.

• Call the binarySearch method with the array, left index 0, right
index n - 1, and the element x.

• If the result is -1, print "Element not present."

• If the result is not -1, print "Element found at index" followed by the
result.

Program:-

import java.util.*;

class GFG {

int binarySearch(int arr[], int l, int r, int x)

if (r >= l && l <= arr.length - 1) {

int mid = l + (r - l) / 2;

if (arr[mid] == x)

return mid;

if (arr[mid] > x)

return binarySearch(arr, l, mid - 1, x);

return binarySearch(arr, mid + 1, r, x);


}

return -1;

public static void main(String args[])

GFG ob = new GFG();

int arr[] = { 2, 3, 4, 10, 40 };

int n = arr.length;

int x = 10;

int result = ob.binarySearch(arr, 0, n - 1, x);

if (result == -1)

System.out.println("Element not present");

else

System.out.println("Element found at index "

+ result);

Output:

Element found at index 3

Time and Space Complexity:-

• Time Complexity: O(log n)

• Space Complexity: O(log n)

12 Write a program to implement Collision resolution in Hash table using


linear probing.

Ans:
Algorithm:-

1. LinearProbingHashTable Class:

• Initialization:

• Initialize the hash table with a given capacity.

• Initialize arrays for keys and values.

• Empty Hash Table:

• Reset the current size and create new arrays for keys and
values.

• Size Information:

• Get the current size of the hash table.

• Full Check:

• Check if the hash table is full.

• Empty Check:

• Check if the hash table is empty.

• Containment Check:

• Check if a key is present in the hash table.

• Hashing Function:

• Hash a key to an index using modulo.

• Insertion:

• Insert a key-value pair into the hash table.

• Resolve collisions using linear probing.

• Retrieval:

• Get the value associated with a key in the hash table.

• Removal:

• Remove a key-value pair from the hash table.

• Handle collisions and rehash the table.

• Print Hash Table:

• Display the current content of the hash table.

2. Main Function:

• User Interaction:

• Create an instance of the LinearProbingHashTable class.


• Allow users to perform various hash table operations:

• Insertion

• Removal

• Retrieval

• Clearing the table

• Displaying the size

• Continue Prompt:

• Allow users to continue with additional operations.

Program:-

import java.util.*;

import java.util.Scanner;

class LinearProbingHashTable {

private int currentSize, maxSize;

private String[] keys;

private String[] vals;

public LinearProbingHashTable(int capacity)

currentSize = 0;

maxSize = capacity;

keys = new String[maxSize];

vals = new String[maxSize];

public void makeEmpty()

currentSize = 0;

keys = new String[maxSize];

vals = new String[maxSize];

public int getSize() { return currentSize; }


public boolean isFull()

return currentSize == maxSize;

public boolean isEmpty() { return getSize() == 0; }

public boolean contains(String key)

return get(key) != null;

private int hash(String key)

return key.hashCode() % maxSize;

public void insert(String key, String val)

int tmp = hash(key);

int i = tmp;

do {

if (keys[i] == null) {

keys[i] = key;

vals[i] = val;

currentSize++;

return;

if (keys[i].equals(key)) {

vals[i] = val;

return;

i = (i + 1) % maxSize;

}
while (i != tmp);

public String get(String key)

int i = hash(key);

while (keys[i] != null) {

if (keys[i].equals(key))

return vals[i];

i = (i + 1) % maxSize;

return null;

public void remove(String key)

if (!contains(key))

return;

int i = hash(key);

while (!key.equals(keys[i]))

i = (i + 1) % maxSize;

keys[i] = vals[i] = null;

for (i = (i + 1) % maxSize; keys[i] != null;

i = (i + 1) % maxSize) {

String tmp1 = keys[i], tmp2 = vals[i];

keys[i] = vals[i] = null;

currentSize--;

insert(tmp1, tmp2);

currentSize--;

public void printHashTable()

{
System.out.println("\nHash Table: ");

for (int i = 0; i < maxSize; i++)

if (keys[i] != null)

System.out.println(keys[i] + " " + vals[i]);

System.out.println();

public class GFG {

public static void main(String[] args)

Scanner scan = new Scanner(System.in);

System.out.println("Hash Table Test\n\n");

System.out.println("Enter size");

LinearProbingHashTable lpht

= new LinearProbingHashTable(scan.nextInt());

char ch;

do

System.out.println("\nHash Table Operations\n");

System.out.println("1. insert ");

System.out.println("2. remove");

System.out.println("3. get");

System.out.println("4. clear");

System.out.println("5. size");

int choice = scan.nextInt();

switch (choice) {

case 1:

System.out.println("Enter key and value");

lpht.insert(scan.next(), scan.next());

break;

case 2:
System.out.println("Enter key");

lpht.remove(scan.next());

break;

case 3:

System.out.println("Enter key");

System.out.println("Value = "

+ lpht.get(scan.next()));

break;

case 4:

lpht.makeEmpty();

System.out.println("Hash Table Cleared\n");

break;

case 5:

System.out.println("Size = "

+ lpht.getSize());

break;

default:

System.out.println("Wrong Entry \n ");

break;

lpht.printHashTable();

System.out.println(

"\nDo you want to continue (Type y or n) \n");

ch = scan.next().charAt(0);

} while (ch == 'Y' || ch == 'y');

Output:
Time and Space Complexity:-
• Time Complexity: O(1) to O(n)

• Space Complexity: O(n)

13 Write a Program to implement selection sort.

Ans:

Algorithm:-

Selection Sort Algorithm:

• Input: An array arr of integers.

• Output: The array sorted in ascending order.

• Procedure:

• Iterate through the array from index 0 to n - 2, where n is the length


of the array.

• For each iteration, find the index (min_idx) of the minimum element
in the unsorted portion of the array (from i + 1 to n - 1).

• Swap the minimum element with the element at index i.

Program:-

class SelectionSort {

void sort(int arr[])

int n = arr.length;

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

int min_idx = i;

for (int j = i + 1; j < n; j++) {

if (arr[j] < arr[min_idx])

min_idx = j;

int temp = arr[min_idx];

arr[min_idx] = arr[i];

arr[i] = temp;

}
void printArray(int arr[])

int n = arr.length;

for (int i = 0; i < n; ++i)

System.out.print(arr[i] + " ");

System.out.println();

public static void main(String args[])

SelectionSort ob = new SelectionSort();

int arr[] = { 64, 25, 12, 22, 11 };

ob.sort(arr);

System.out.println("Sorted array");

ob.printArray(arr);

Output:

Sorted array

11 12 22 25 64

Time and Space Complexity:-

• Time Complexity: O(n^2)

• Space Complexity: O(1)

14 Write a Program to implement merge sort.

Ans:

Algorithm:-

Merge Sort Algorithm:


• Input: An array arr of integers.

• Output: The array sorted in ascending order.

• Procedure:

• Divide the array into two halves.

• Recursively apply Merge Sort to each half.

• Merge the two sorted halves into a single sorted array.

Program:-

class MergeSort {

void merge(int arr[], int l, int m, int r)

int n1 = m - l + 1;

int n2 = r - m;

int L[] = new int[n1];

int R[] = new int[n2];

for (int i = 0; i < n1; ++i)

L[i] = arr[l + i];

for (int j = 0; j < n2; ++j)

R[j] = arr[m + 1 + j];

int i = 0, j = 0;

int k = l;

while (i < n1 && j < n2) {

if (L[i] <= R[j]) {

arr[k] = L[i];

i++;

else {

arr[k] = R[j];

j++;

k++;

}
while (i < n1) {

arr[k] = L[i];

i++;

k++;

while (j < n2) {

arr[k] = R[j];

j++;

k++;

void sort(int arr[], int l, int r)

if (l < r) {

int m = (l + r) / 2;

sort(arr, l, m);

sort(arr, m + 1, r);

merge(arr, l, m, r);

static void printArray(int arr[])

int n = arr.length;

for (int i = 0; i < n; ++i)

System.out.print(arr[i] + " ");

System.out.println();

public static void main(String args[])

int arr[] = { 12, 11, 13, 5, 6, 7 };

System.out.println("Given Array");
printArray(arr);

MergeSort ob = new MergeSort();

ob.sort(arr, 0, arr.length - 1);

System.out.println("\nSorted array");

printArray(arr);

Output:

Given Array

12 11 13 5 6 7

Sorted array

5 6 7 11 12 13

Time and Space Complexity:-

• Time Complexity: O(n log n)

• Space Complexity: O(n)

15 Write a program to print pre order traversal of a tree.

Ans:

Algorithm:-

PreorderTraversal(node):

1. if node is null:

2. return

3. print node.item + "->"

4. PreorderTraversal(node.left)

5. PreorderTraversal(node.right)

Algorithm Main():

1. Create a new Tree object called "tree"

2. Set tree.root to a new Node with item 1


3. Set tree.root.left to a new Node with item 12

4. Set tree.root.right to a new Node with item 9

5. Set tree.root.left.left to a new Node with item 5

6. Set tree.root.left.right to a new Node with item 6

7. Print "Preorder traversal"

8. Call tree.preorder(tree.root)

Program:-

class Node {

int item;

Node left, right;

public Node(int key) {

item = key;

left = right = null;

class Tree {

Node root;

Tree() {

root = null;

void preorder(Node node) {

if (node == null)

return;

System.out.print(node.item + "->");

preorder(node.left);

preorder(node.right);

public static void main(String[] args) {

Tree tree = new Tree();

tree.root = new Node(1);


tree.root.left = new Node(12);

tree.root.right = new Node(9);

tree.root.left.left = new Node(5);

tree.root.left.right = new Node(6);

System.out.println("\nPreorder traversal ");

tree.preorder(tree.root);

Output:

Preorder traversal

1->12->5->6->9->

Time and Space Complexity:-

• Time Complexity: O(n)

• Space Complexity: O(n)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy