DS Practical ZIBRAN
DS Practical ZIBRAN
SUBMITTED BY:-
SECTION: 19
SEMESTER: III
1 Write a program to reverse an array without using an additional array.
Ans:
Algorithm:-
1. Input Size:
2. Array Input:
Program:-
import java.util.Scanner;
array[i] = scanner.nextInt();
reverseArray(array);
System.out.println("Reversed array:");
int startIndex = 0;
array[startIndex] = array[endIndex];
array[endIndex] = temp;
startIndex++;
endIndex--;
Output:
Enter 5 elements:
12345
Reversed array:
54321
Time and Space Complexity:-
Ans:
Algorithm:-
1. Function print2largest:
2. Main Function:
• Create an Integer array arr with values {12, 35, 1, 10, 34, 1}.
• Call the print2largest function with the array arr and its length n.
3. End of Algorithm.
Program:-
import java.util.*;
class GFG {
Arrays.sort(arr, Collections.reverseOrder());
if (arr[i] != arr[0]) {
return;
}
int n = arr.length;
print2largest(arr, n);
Output:
Ans:
Algorithm:-
2. Node Class:
• Create a class Node with data and a reference to the next node.
• Update the next reference of the previous node to skip the node
to be deleted.
• Traverse the linked list from head to the end, printing each
node's data.
6. Main Function:
Program:-
import java.io.*;
class LinkedList {
Node head;
class Node {
int data;
Node next;
Node(int d)
data = d;
next = null;
}
new_node.next = head;
head = new_node;
if (head == null)
return;
if (position == 0) {
head = temp.next;
return;
i++)
temp = temp.next;
return;
temp.next= next;
tnode = tnode.next;
}
llist.push(7);
llist.push(1);
llist.push(3);
llist.push(2);
llist.push(8);
llist.printList();
System.out.println(
llist.printList();
Output:
Ans:
Algorithm:-
• Initialize an array arr with the data of the first two nodes
and sort it.
3. Main Function:
Program:-
import java.util.Arrays;
class Node {
class Main {
return Integer.MAX_VALUE;
arr[1] = arr[0];
arr[0] = curr.data;
arr[1] = curr.data;
curr = curr.next;
return arr[1];
head.data = 1;
head.next.data = 34;
head.next.next.data = 10;
head.next.next.next.data = 1;
head.next.next.next.next.data = 35;
head.next.next.next.next.next.data = 12;
if (secondSmallest == Integer.MAX_VALUE) {
System.out.println(
else {
System.out.println(
+ secondSmallest + ".");
Output:
The second smallest element in the list is 10.
Ans:
Algorithm:-
1. Define Function fib:
• If n is 0, return a.
2. Main Function:
Program:-
public class fibonacci {
int a = 0, b = 1, c;
if (n == 0)
return a;
c = a + b;
a = b;
b = c;
return b;
int n = 9;
System.out.println(fib(n));
};
Output:
34
Ans:
Algorithm:-
1. Define Function towerOfHanoi:
• Input:
• Base Case:
• Recursive Steps:
• Move n-1 disks from the source rod to the auxiliary rod
using the destination rod as an auxiliary.
2. Main Function:
• The function will print the sequence of moves to solve the Tower
of Hanoi problem.
Program:-
class GFG {
if (n == 1) {
System.out.println("Move disk 1 from rod " + from_rod + " to rod " + to_rod);
return;
System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod);
{
int n = 4; // Number of disks
Output:
Move disk 1 from rod A to rod B
Ans:
Algorithm:-
• While the sorted stack is not empty and the top of the
sorted stack is greater than current:
• Print the kth largest element from the top of the sorted stack.
3. Main Function:
• Read n integers from the user and push them onto the input
stack.
• Find and print the kth largest element from the sorted stack
using the findKthLargestNum function.
Program:-
import java.util.*;
public static Stack < Integer > sortStack(Stack < Integer > input) {
Stack < Integer > inputStack = new Stack < Integer > ();
int n = in .nextInt();
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);
findKthLargestNum(temp, k);
Ans:
Algorithm:-
• Pop the top two values (val1 and val2) from the stack.
2. Main Function:
Program:-
import java.util.Stack;
char c = exp.charAt(i);
if (Character.isDigit(c))
stack.push(c - '0');
else {
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();
+ evaluatePostfix(exp));
Output:
postfix evaluation: -4
Ans:
Algorithm:-
2. Define Functions:
• deQueue(Queue q):
• If the queue has only one element, set front and rear to
null.
• displayQueue(Queue q):
• Iterate through the queue and print each element until the
linked list forms a complete circle.
Program:-
import java.io.*;
import java.util.*;
int data;
Node link;
temp.data = value;
if (q.front == null)
q.front = temp;
else
q.rear.link = temp;
q.rear = temp;
q.rear.link = q.front;
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
value = temp.data;
q.front = q.front.link;
q.rear.link = q.front;
return value;
System.out.printf(
temp = temp.link;
System.out.printf("%d", temp.data);
}
enQueue(q, 14);
enQueue(q, 22);
enQueue(q, 6);
displayQueue(q);
deQueue(q));
deQueue(q));
displayQueue(q);
enQueue(q, 9);
enQueue(q, 20);
displayQueue(q);
Output:
Deleted value = 14
Deleted value = 22
Ans:
Algorithm:-
• 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.
• Insert four tasks with different priorities into the priority queue.
Program:-
import java.util.ArrayList;
class PriorityQueue
ArrayList<Pair> queue;
public PriorityQueue() {
this.queue.add(pair);
int maxIdx = 0;
maxIdx = i;
maxIdx++;
this.queue.remove(this.queue.size() - 1);
return val;
String val;
int priority;
this.val = val;
this.priority = priority;
}
public static void main(String[] args) {
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
Ans:
Algorithm:-
• Input:
• Output:
2. Procedure:
• Check if r is greater than or equal to l (base case).
• Call the binarySearch method with the array, left index 0, right
index n - 1, and the element x.
• If the result is not -1, print "Element found at index" followed by the
result.
Program:-
import java.util.*;
class GFG {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return -1;
int n = arr.length;
int x = 10;
if (result == -1)
else
+ result);
Output:
Ans:
Algorithm:-
1. LinearProbingHashTable Class:
• Initialization:
• Reset the current size and create new arrays for keys and
values.
• Size Information:
• Full Check:
• Empty Check:
• Containment Check:
• Hashing Function:
• Insertion:
• Retrieval:
• Removal:
2. Main Function:
• User Interaction:
• Insertion
• Removal
• Retrieval
• Continue Prompt:
Program:-
import java.util.*;
import java.util.Scanner;
class LinearProbingHashTable {
currentSize = 0;
maxSize = capacity;
currentSize = 0;
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);
int i = hash(key);
if (keys[i].equals(key))
return vals[i];
i = (i + 1) % maxSize;
return null;
if (!contains(key))
return;
int i = hash(key);
while (!key.equals(keys[i]))
i = (i + 1) % maxSize;
i = (i + 1) % maxSize) {
currentSize--;
insert(tmp1, tmp2);
currentSize--;
{
System.out.println("\nHash Table: ");
if (keys[i] != null)
System.out.println();
System.out.println("Enter size");
LinearProbingHashTable lpht
= new LinearProbingHashTable(scan.nextInt());
char ch;
do
System.out.println("2. remove");
System.out.println("3. get");
System.out.println("4. clear");
System.out.println("5. size");
switch (choice) {
case 1:
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();
break;
case 5:
System.out.println("Size = "
+ lpht.getSize());
break;
default:
break;
lpht.printHashTable();
System.out.println(
ch = scan.next().charAt(0);
Output:
Time and Space Complexity:-
• Time Complexity: O(1) to O(n)
Ans:
Algorithm:-
• Procedure:
• 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).
Program:-
class SelectionSort {
int n = arr.length;
int min_idx = i;
min_idx = j;
arr[min_idx] = arr[i];
arr[i] = temp;
}
void printArray(int arr[])
int n = arr.length;
System.out.println();
ob.sort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
Output:
Sorted array
11 12 22 25 64
Ans:
Algorithm:-
• Procedure:
Program:-
class MergeSort {
int n1 = m - l + 1;
int n2 = r - m;
int i = 0, j = 0;
int k = l;
arr[k] = L[i];
i++;
else {
arr[k] = R[j];
j++;
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
arr[k] = R[j];
j++;
k++;
if (l < r) {
int m = (l + r) / 2;
sort(arr, l, m);
sort(arr, m + 1, r);
merge(arr, l, m, r);
int n = arr.length;
System.out.println();
System.out.println("Given Array");
printArray(arr);
System.out.println("\nSorted array");
printArray(arr);
Output:
Given Array
12 11 13 5 6 7
Sorted array
5 6 7 11 12 13
Ans:
Algorithm:-
PreorderTraversal(node):
1. if node is null:
2. return
4. PreorderTraversal(node.left)
5. PreorderTraversal(node.right)
Algorithm Main():
8. Call tree.preorder(tree.root)
Program:-
class Node {
int item;
item = key;
class Tree {
Node root;
Tree() {
root = null;
if (node == null)
return;
System.out.print(node.item + "->");
preorder(node.left);
preorder(node.right);
tree.preorder(tree.root);
Output:
Preorder traversal
1->12->5->6->9->