0% found this document useful (0 votes)
9 views

[ADA] lab file

a readable notes
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)
9 views

[ADA] lab file

a readable notes
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/ 66

//Shiv Sundar Singh

22SCSE1011854

GALGOTIAS UVIVERSITY

ANALYSIS AND DESIGN OF ALGORITHM

LAB FILE

Name: - SHIV SUNDAR SINGH


Admission No: - 22SCSE1011854
Section -10

Submitted to Dr. Ashokh Kumar Yadav


//Shiv Sundar Singh
22SCSE1011854

Linked List
//Shiv Sundar Singh 22SCSE1011854

// Node class representing each element in the linked list

class Node {

int data; // Value of the node

Node next; // Reference to the next node

// Constructor to initialize the node

public Node(int data) {

this.data = data;

this.next = null;

// LinkedList class to manage the linked list operations

class LinkedList {

private Node head; // Head of the list

// Constructor to initialize the linked list

public LinkedList() {

this.head = null;

// Method to insert a new node at the end of the list

public void insert(int data) {

Node newNode = new Node(data);

if (head == null) {

head = newNode;

} else {

Node current = head;


//Shiv Sundar Singh
22SCSE1011854

while (current.next != null) {

current = current.next;

current.next = newNode;

// Method to delete a node with a specific value

public void delete(int data) {

if (head == null) {

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

return;

if (head.data == data) {

head = head.next;

return;

Node current = head;

while (current.next != null && current.next.data != data) {

current = current.next;

if (current.next == null) {

System.out.println("Value not found in the list");

return;

current.next = current.next.next;

}
//Shiv Sundar Singh
22SCSE1011854

// Method to display the linked list

public void display() {

if (head == null) {

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

return;

Node current = head;

while (current != null) {

System.out.print(current.data + " -> ");

current = current.next;

System.out.println("null");

// Method to search for a value in the linked list

public boolean search(int data) {

Node current = head;

while (current != null) {

if (current.data == data) {

return true;

}
current = current.next;

return false;

// Main method to demonstrate the linked list operations

public static void main(String[] args) {

LinkedList list = new LinkedList();


//Shiv Sundar Singh
22SCSE1011854

// Inserting elements

list.insert(10);

list.insert(20);

list.insert(30);

list.insert(40);

// Displaying the list

System.out.println("Linked List:");

list.display();

// Searching for an element

System.out.println("Search for 20: " + list.search(20));

System.out.println("Search for 50: " + list.search(50));

// Deleting an element

list.delete(20);

System.out.println("Linked List after deleting 20:");

list.display();

}
//Shiv Sundar Singh
22SCSE1011854

Stack
//Shiv Sundar Singh 22SCSE1011854

public class StackUsingLinkedList<T> {

private Node<T> top; // Top of the stack

// Node class

private static class Node<T> {

private T data;

private Node<T> next;

public Node(T data) {

this.data = data;

// Push method to add an element to the stack

public void push(T data) {

Node<T> newNode = new Node<>(data);

newNode.next = top; // Link the new node to the previous top node

top = newNode; // Update the top to the new node

// Pop method to remove an element from the stack

public T pop() {

if (top == null) {

throw new IllegalStateException("Stack is empty");

T data = top.data;

top = top.next; // Update the top to the next node


//Shiv Sundar Singh
22SCSE1011854

return data;

// Peek method to view the top element of the stack without removing it

public T peek() {

if (top == null) {

throw new IllegalStateException("Stack is empty");

return top.data;

// isEmpty method to check if the stack is empty

public boolean isEmpty() {

return top == null;

// Main method to test the stack

public static void main(String[] args) {

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

stack.push(10);

stack.push(20);

stack.push(30);

System.out.println("Top element is: " + stack.peek()); // Should print 30

System.out.println("Popped element is: " + stack.pop()); // Should print 30

System.out.println("Top element after pop is: " + stack.peek()); // Should print 20

System.out.println("Is stack empty? " + stack.isEmpty()); // Should print false

stack.pop();
//Shiv Sundar Singh
22SCSE1011854

stack.pop();

System.out.println("Is stack empty after popping all elements? " + stack.isEmpty()); // Should
print true

}
//Shiv Sundar Singh
22SCSE1011854

Find no is divisible by 2 or not without using %.


//Shiv Sundar Singh

22SCSE1011854 public class

DivisibilityBy2 {

public static void main(String[] args) {

int number = 4; // Change this number to test different cases

if (isDivisibleBy2(number)) {

System.out.println(number + " is divisible by 2.");

} else {

System.out.println(number + " is not divisible by 2.");

public static boolean isDivisibleBy2(int number) {

// Using bitwise AND to check the least significant bit

return (number & 1) == 0;

}
//Shiv Sundar Singh
22SCSE1011854

Find the kth bit


//Shiv Sundar Singh

22SCSE1011854 public class

KthBitFinder {

public static void main(String[] args) {

int number = 29; // Example number

int k = 3; // Example k-th bit to find (0-based index)

int bit = findKthBit(number, k);

System.out.println("The " + k + "-th bit of " + number + " is: " + bit);

public static int findKthBit(int number, int k) {

// Shift the number right by k positions and perform a bitwise AND with 1

return (number >> k) & 1;

}
//Shiv Sundar Singh
22SCSE1011854

Find out the two consecutives 1’s in binary representation of a no.


public class ConsecutiveOnesFinder { //Shiv Sundar Singh

22SCSE1011854 public static void main(String[] args) {

int number = 29; // Example number

if (hasConsecutiveOnes(number)) {

System.out.println(number + " has consecutive 1's in its binary representation.");

} else {

System.out.println(number + " does not have consecutive 1's in its binary


representation.");

public static boolean hasConsecutiveOnes(int number) {

// Perform a bitwise AND between the number and the number shifted right by one

// If there are consecutive 1's, the result will be non-zero

return (number & (number >> 1)) != 0;

}
//Shiv Sundar Singh
22SCSE1011854

Find out no is 2^i, yes or no


public class PowerOfTwoChecker { //Shiv Sundar Singh 22SCSE1011854

public static void main(String[] args) {

int number = 16; // Example number

if (isPowerOfTwo(number)) {

System.out.println(number + " is a power of 2.");

} else {

System.out.println(number + " is not a power of 2.");

public static boolean isPowerOfTwo(int number) {

// Check if the number is greater than 0 and only one bit is set in its binary representation

return (number > 0) && ((number & (number - 1)) == 0);

}
//Shiv Sundar Singh
22SCSE1011854

Swap two no by 4 different ways


//Shiv Sundar Singh

22SCSE1011854 import

java.util.Scanner;

public class SwapNumbers {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first number (a): ");

int a = scanner.nextInt();

System.out.print("Enter the second number (b): ");

int b = scanner.nextInt();

System.out.println("Original values: a = " + a + ", b = " + b);

// Method 1: Using a Temporary Variable

swapUsingTemp(a, b);

// Method 2: Using Addition and Subtraction

swapUsingAdditionSubtraction(a, b);

// Method 3: Using Multiplication and Division

swapUsingMultiplicationDivision(a, b);

// Method 4: Using Bitwise XOR

swapUsingXOR(a, b);

scanner.close();

}
//Shiv Sundar Singh
22SCSE1011854

// Method 1: Using a Temporary Variable

public static void swapUsingTemp(int a, int b) {

System.out.println("\nSwapping using a temporary variable:");

int temp = a;

a = b;

b = temp;

System.out.println("Swapped values: a = " + a + ", b = " + b);

// Method 2: Using Addition and Subtraction

public static void swapUsingAdditionSubtraction(int a, int b) {

System.out.println("\nSwapping using addition and subtraction:");

a = a + b; // a now holds the sum of a and b

b = a - b; // b is now the original a

a = a - b; // a is now the original b

System.out.println("Swapped values: a = " + a + ", b = " + b);

// Method 3: Using Multiplication and Division

public static void swapUsingMultiplicationDivision(int a, int b) {

System.out.println("\nSwapping using multiplication and division:");

if (b != 0) { // Check to avoid division by zero

a = a * b; // a now holds the product of a and b

b = a / b; // b is now the original a

a = a / b; // a is now the original b

} else {

System.out.println("Cannot swap using multiplication and division as b is 0 (division by


zero is not allowed).");

System.out.println("Swapped values: a = " + a + ", b = " + b);

}
//Shiv Sundar Singh
22SCSE1011854

// Method 4: Using Bitwise XOR

public static void swapUsingXOR(int a, int b) {

System.out.println("\nSwapping using bitwise XOR:");

a = a ^ b; // a now holds the XOR of a and b

b = a ^ b; // b is now the original a

a = a ^ b; // a is now the original b

System.out.println("Swapped values: a = " + a + ", b = " + b);

}
//Shiv Sundar Singh
22SCSE1011854

Find the kth bit by 3 different ways and toggle the bit.
import java.util.Scanner;

//Shiv Sundar Singh

22SCSE1011854 public class

KthBitToggler {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

int number = scanner.nextInt();

System.out.print("Enter the k-th bit to toggle (0-based index): ");

int k = scanner.nextInt();

System.out.println("Original number: " + number);

// Method 1: Using Right Shift and Bitwise AND

toggleKthBitMethod1(number, k);

// Method 2: Using Bitwise Left Shift and Bitwise AND

toggleKthBitMethod2(number, k);

// Method 3: Using Bitwise XOR with 1 Shifted by k

toggleKthBitMethod3(number, k);

scanner.close();

// Method 1: Using Right Shift and Bitwise AND

public static void toggleKthBitMethod1(int number, int k) {

int mask = 1 << k; // Create a mask with the k-th bit set
//Shiv Sundar Singh
22SCSE1011854

int result = number ^ mask; // Toggle the k-th bit using XOR

System.out.println("Method 1: Toggled number: " + result);

// Method 2: Using Bitwise Left Shift and Bitwise AND

public static void toggleKthBitMethod2(int number, int k) {

int mask = 1 << k; // Create a mask with the k-th bit set

int result = number ^ mask; // Toggle the k-th bit using XOR

System.out.println("Method 2: Toggled number: " + result);

// Method 3: Using Bitwise XOR with 1 Shifted by k

public static void toggleKthBitMethod3(int number, int k) {

int result = number ^ (1 << k); // Toggle the k-th bit using XOR

System.out.println("Method 3: Toggled number: " + result);

}
//Shiv Sundar Singh
22SCSE1011854

Find out the student with 3 activities. All students assigned 2 activities
except one
public class StudentActivities { //Shiv Sundar Singh

22SCSE1011854 public static void main(String[] args) {

int[] activities = {1, 2, 3, 2, 1, 3, 2}; // Example array of activities

int n = activities.length;

// Find the student with 3 activities

int studentWithThreeActivities = findStudentWithThreeActivities(activities, n);

if (studentWithThreeActivities != -1) {

System.out.println("Student " + studentWithThreeActivities + " has 3 activities.");

} else {

System.out.println("No student has 3 activities.");

public static int findStudentWithThreeActivities(int[] activities, int n) {

int studentWithThreeActivities = -1;

int[] activityCounts = new int[n + 1]; // Array to store activity counts for each student

// Count the activities for each student

for (int activity : activities) {

activityCounts[activity]++;

// Find the student with 3 activities

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

if (activityCounts[i] == 3) {

studentWithThreeActivities = i;
//Shiv Sundar Singh
22SCSE1011854

break;

return studentWithThreeActivities;

}
//Shiv Sundar Singh
22SCSE1011854

ADDITION OF TWO MATRICES


//Shiv Sundar Singh

22SCSE1011854 public class

MatrixAddition {

public static void main(String[] args) {

int[][] matrix1 = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

int[][] matrix2 = {

{9, 8, 7},

{6, 5, 4},

{3, 2, 1}

};

int rows = matrix1.length;

int columns = matrix1[0].length;

// Resultant matrix to store the sum

int[][] result = new int[rows][columns];

// Perform addition

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

for (int j = 0; j < columns; j++) {

result[i][j] = matrix1[i][j] + matrix2[i][j];

// Display the result


//Shiv Sundar Singh
22SCSE1011854

System.out.println("Matrix Addition Result:");

displayMatrix(result);

// Method to display a matrix

public static void displayMatrix(int[][] matrix) {

for (int[] row : matrix) {

for (int element : row) {

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

System.out.println();

}
//Shiv Sundar Singh
22SCSE1011854

Multiplication of two matrix


public class MatrixMultiplication { //Shiv Sundar Singh 22SCSE1011854

public static void main(String[] args) {

// Define the matrices

int[][] matrix1 = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

int[][] matrix2 = {

{9, 8, 7},

{6, 5, 4},

{3, 2, 1}

};

// Perform matrix multiplication

int[][] result = multiplyMatrices(matrix1, matrix2);

// Display the result

System.out.println("Matrix Multiplication Result:");

displayMatrix(result);

// Method to perform matrix multiplication

public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) {

int rows1 = matrix1.length;

int columns1 = matrix1[0].length;

int rows2 = matrix2.length;

int columns2 = matrix2[0].length;


//Shiv Sundar Singh
22SCSE1011854

// Check if matrices can be multiplied

if (columns1 != rows2) {

throw new IllegalArgumentException("Matrices cannot be multiplied. Number of columns


of the first matrix must be equal to the number of rows of the second matrix.");

// Initialize the resultant matrix

int[][] result = new int[rows1][columns2];

// Perform matrix multiplication

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

for (int j = 0; j < columns2; j++) {

for (int k = 0; k < columns1; k++) {

result[i][j] += matrix1[i][k] * matrix2[k][j];

return result;

// Method to display a matrix

public static void displayMatrix(int[][] matrix) {

for (int[] row : matrix) {

for (int element : row) {

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

System.out.println();

}
//Shiv Sundar Singh
22SCSE1011854

Display matrix in snake order


public class SnakeMatrixDisplay {

public static void main(String[] args) { //Shiv Sundar Singh 22SCSE1011854

int[][] matrix = {

{1, 2, 3, 4},

{5, 6, 7, 8},

{9, 10, 11, 12},

{13, 14, 15, 16}

};

displayMatrixInSnakeOrder(matrix);

public static void displayMatrixInSnakeOrder(int[][] matrix) {

int rows = matrix.length;

int columns = matrix[0].length;

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

// For odd rows, reverse the order of elements

if (i % 2 == 1) {

for (int j = columns - 1; j >= 0; j--) {

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

} else {

for (int j = 0; j < columns; j++) {

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

}
//Shiv Sundar Singh
22SCSE1011854

Display boundary value of matrix (hide the non-boundary value for


advance programmers)
public class BoundaryMatrixDisplay {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};

displayBoundary(matrix);
}

public static void displayBoundary(int[][] matrix) {


int rows = matrix.length;
int columns = matrix[0].length;

// Display top row


for (int j = 0; j < columns; j++) {
System.out.print(matrix[0][j] + " ");
}
System.out.println();

// Display right column (excluding top and bottom elements)


for (int i = 1; i < rows - 1; i++) {
System.out.print(matrix[i][columns - 1] + " ");
}
System.out.println();

// Display bottom row (in reverse order)


for (int j = columns - 1; j >= 0; j--) {
System.out.print(matrix[rows - 1][j] + " ");
}
System.out.println();

// Display left column (excluding top and bottom elements, in reverse order)
for (int i = rows - 2; i > 0; i--) {
System.out.print(matrix[i][0] + " ");
}
}
}
//Shiv Sundar Singh
22SCSE1011854

Given two numbers l and r, find the maximum XOR value of the numbers
in between l and r.
public class MaximumXORInRange //Shiv Sundar Singh 22SCSE1011854

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

int l = 5; // Example value for l

int r = 8; // Example value for r

int maxXOR = findMaximumXOR(l, r);

System.out.println("Maximum XOR value between " + l + " and " + r + " is: " + maxXOR);

public static int findMaximumXOR(int l, int r) {

int max = 0;

for (int i = l; i <= r; i++) {

for (int j = i; j <= r; j++) {

int xor = i ^ j; // Calculate XOR of the two numbers

max = Math.max(max, xor); // Update max if current XOR is greater

return max;

}
//Shiv Sundar Singh
22SCSE1011854

Marks Moderator: if you are getting marks less then upto 2 of next
multiple of 5, then your marks will be moderated to next multiple of 5. If
marks is less then 48, then you fail, if you got more then 95 will be given
100.
//Shiv Sundar Singh

22SCSE1011854 public class

MarksModerator {

public static void main(String[] args) {

int marks = 72; // Example marks

int moderatedMarks = moderateMarks(marks);

System.out.println("Original Marks: " + marks);

System.out.println("Moderated Marks: " + moderatedMarks);

public static int moderateMarks(int marks) {

// Moderation rules

if (marks < 48) {

return 0; // Fail

} else if (marks > 95) {

return 100; // Maximum marks

} else {

int nextMultipleOf5 = ((marks + 4) / 5) * 5; // Round up to the next multiple of 5

if (nextMultipleOf5 - marks < 3) {

return nextMultipleOf5; // Moderate to the next multiple of 5

} else {

return marks; // No moderation needed

}
//Shiv Sundar Singh
22SCSE1011854

Two Kangaroos k1 and k2 starts jumping by j1 and j2 meter from x1, x2


point. Find out they will meet in the way or not. If they meet then where
they meet and after how many jumps. Where 1<=j1,j2<=1000,
0<=x1,x2<=1000.
//Shiv Sundar Singh 22SCSE1011854

public class KangarooMeeting {

public static void main(String[] args) {

int x1 = 0; // Starting point of k1

int j1 = 3; // Jump distance of k1

int x2 = 5; // Starting point of k2

int j2 = 4; // Jump distance of k2

int[] meetingPoint = findMeetingPoint(x1, j1, x2, j2);

if (meetingPoint[0] != -1) {

System.out.println("The kangaroos meet at position " + meetingPoint[0] + " after " +


meetingPoint[1] + " jumps.");

} else {

System.out.println("The kangaroos do not meet.");

public static int[] findMeetingPoint(int x1, int j1, int x2, int j2) {

int[] meetingPoint = {-1, -1}; // Initialize with no meeting point

for (int i = 0; i <= 1000; i++) { // Maximum 1000 jumps

x1 += j1;

x2 += j2;

if (x1 == x2) { // Kangaroos meet

meetingPoint[0] = x1; // Meeting point


//Shiv Sundar Singh
22SCSE1011854

meetingPoint[1] = i + 1; // Number of jumps (1-based indexing)

break;

return meetingPoint;

}
//Shiv Sundar Singh
22SCSE1011854

Write a program to sort the array using Bubble sort and find out the best case
and worst-case scenario.
//Shiv Sundar Singh

22SCSE1011854 public class

BubbleSort {

public static void main(String[] args) {

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

System.out.println("Original Array:");

printArray(arr);

bubbleSort(arr);

System.out.println("\nSorted Array:");

printArray(arr);

int[] bestCaseArr = {11, 12, 22, 25, 34, 64, 90}; // Best-case scenario

int[] worstCaseArr = {90, 64, 34, 25, 22, 12, 11}; // Worst-case scenario

System.out.println("\nBest Case Array:");

printArray(bestCaseArr);

System.out.println("Comparisons in best case: " + bubbleSortWithCount(bestCaseArr));

System.out.println("\nWorst Case Array:");

printArray(worstCaseArr);

System.out.println("Comparisons in worst case: " + bubbleSortWithCount(worstCaseArr));

public static void bubbleSort(int[] arr) {

int n = arr.length;

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


//Shiv Sundar Singh
22SCSE1011854

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

if (arr[j] > arr[j + 1])

int temp = arr[j];

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

arr[j + 1] = temp;

public static int bubbleSortWithCount(int[] arr) {

int n = arr.length;

int comparisons = 0;

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

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

comparisons++;

if (arr[j] > arr[j + 1]) {

// Swap arr[j] and arr[j+1]

int temp = arr[j];

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

arr[j + 1] = temp;

return comparisons;

public static void printArray(int[] arr) {

for (int num : arr) {

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

System.out.println();

}
//Shiv Sundar Singh
22SCSE1011854

Write a program to sort the array using Insertion sort and find out the best
case and worst-case scenario.

//Shiv Sundar Singh

22SCSE1011854 public class

InsertionSort {

public static void main(String[] args) {

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

System.out.println("Original Array:");

printArray(arr);

insertionSort(arr);

System.out.println("\nSorted Array:");

printArray(arr);

int[] bestCaseArr = {11, 12, 22, 25, 34, 64, 90}; // Best-case scenario

int[] worstCaseArr = {90, 64, 34, 25, 22, 12, 11}; // Worst-case scenario

System.out.println("\nBest Case Array:");

printArray(bestCaseArr);

System.out.println("Comparisons in best case: " + insertionSortWithCount(bestCaseArr));

System.out.println("\nWorst Case Array:");

printArray(worstCaseArr);

System.out.println("Comparisons in worst case: " + insertionSortWithCount(worstCaseArr));

public static void insertionSort(int[] arr) {

int n = arr.length;
//Shiv Sundar Singh
22SCSE1011854

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

int key = arr[i];

int j = i - 1;

// Move elements of arr[0..i-1], that are greater than key,

// to one position ahead of their current position

while (j >= 0 && arr[j] > key) {

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

j = j - 1;

arr[j + 1] = key;

public static int insertionSortWithCount(int[] arr) {

int n = arr.length;

int comparisons = 0;

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

int key = arr[i];

int j = i - 1;

// Move elements of arr[0..i-1], that are greater than key,

// to one position ahead of their current position


while (j >= 0 && arr[j] > key) {

comparisons++;

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

j = j - 1;

arr[j + 1] = key;

return comparisons;
//Shiv Sundar Singh
22SCSE1011854

public static void printArray(int[] arr) {

for (int num : arr) {

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

System.out.println();

}
//Shiv Sundar Singh
22SCSE1011854

Write a program to sort the array using Selection sort and find out the
best case and worst-case scenario.
//Shiv Sundar Singh

22SCSE1011854 public class

SelectionSort {

public static void main(String[] args) {

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

System.out.println("Original Array:");

printArray(arr);

selectionSort(arr);

System.out.println("\nSorted Array:");

printArray(arr);

int[] bestCaseArr = {11, 12, 22, 25, 34, 64, 90}; // Best-case scenario

int[] worstCaseArr = {90, 64, 34, 25, 22, 12, 11}; // Worst-case scenario

System.out.println("\nBest Case Array:");

printArray(bestCaseArr);

System.out.println("Comparisons in best case: " + selectionSortWithCount(bestCaseArr));

System.out.println("\nWorst Case Array:");

printArray(worstCaseArr);

System.out.println("Comparisons in worst case: " + selectionSortWithCount(worstCaseArr));

public static void selectionSort(int[] arr) {

int n = arr.length;

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

int minIndex = i;
//Shiv Sundar Singh
22SCSE1011854

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

if (arr[j] < arr[minIndex]) {

minIndex = j;

// Swap the found minimum element with the first element

int temp = arr[minIndex];

arr[minIndex] = arr[i];

arr[i] = temp;

public static int selectionSortWithCount(int[] arr) {

int n = arr.length;

int comparisons = 0;

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

int minIndex = i;

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

comparisons++;

if (arr[j] < arr[minIndex]) {

minIndex = j;

// Swap the found minimum element with the first element

int temp = arr[minIndex];

arr[minIndex] = arr[i];

arr[i] = temp;

return comparisons;

}
//Shiv Sundar Singh
22SCSE1011854

public static void printArray(int[] arr) {

for (int num : arr) {

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

System.out.println();

}
//Shiv Sundar Singh
22SCSE1011854

Write a program to sort the array using Merge sort and find out the best
case and worst-case scenario.
//Shiv Sundar Singh

22SCSE1011854 public class

MergeSort {

public static void main(String[] args) {

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

System.out.println("Original Array:");

printArray(arr);

mergeSort(arr, 0, arr.length - 1);

System.out.println("\nSorted Array:");

printArray(arr);

int[] bestCaseArr = {11, 12, 22, 25, 34, 64, 90}; // Best-case scenario

int[] worstCaseArr = {90, 64, 34, 25, 22, 12, 11}; // Worst-case scenario

System.out.println("\nBest Case Array:");

printArray(bestCaseArr);

System.out.println("Comparisons in best case: " + mergeSortWithCount(bestCaseArr, 0,


bestCaseArr.length - 1));

System.out.println("\nWorst Case Array:");

printArray(worstCaseArr);

System.out.println("Comparisons in worst case: " + mergeSortWithCount(worstCaseArr, 0,


worstCaseArr.length - 1));

public static void mergeSort(int[] arr, int l, int r) {

if (l < r) {

// Find the middle point


//Shiv Sundar Singh
22SCSE1011854

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

// Sort first and second halves

mergeSort(arr, l, m);

mergeSort(arr, m + 1, r);

// Merge the sorted halves

merge(arr, l, m, r);

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

int n1 = m - l + 1;

int n2 = r - m;

// Create temporary arrays

int[] L = new int[n1];

int[] R = new int[n2];

// Copy data to temporary arrays L[] and R[]

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];

// Merge the temporary arrays

int i = 0, j = 0;

// Initial index of merged subarray array


//Shiv Sundar Singh
22SCSE1011854

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++;

// Copy remaining elements of L[] if any

while (i < n1) {

arr[k] = L[i];

i++;

k++;

// Copy remaining elements of R[] if any

while (j < n2) {

arr[k] = R[j];

j++;

k++;

public static int mergeSortWithCount(int[] arr, int l, int r) {

int comparisons = 0;

if (l < r) {

// Find the middle point


//Shiv Sundar Singh
22SCSE1011854

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

// Sort first and second halves

comparisons += mergeSortWithCount(arr, l, m);

comparisons += mergeSortWithCount(arr, m + 1, r);

// Merge the sorted halves

comparisons += mergeWithCount(arr, l, m, r);

return comparisons;

public static int mergeWithCount(int[] arr, int l, int m, int r) {

int comparisons = 0;

int n1 = m - l + 1;

int n2 = r - m;

// Create temporary arrays

int[] L = new int[n1];

int[] R = new int[n2];

// Copy data to temporary arrays L[] and R[]

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];

// Merge the temporary arrays

int i = 0, j = 0;
//Shiv Sundar Singh
22SCSE1011854

// Initial index of merged subarray array

int k = l;

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

comparisons++;

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

arr[k] = L[i];

i++;

} else {

arr[k] = R[j];

j++;

k++;

// Copy remaining elements of L[] if any

while (i < n1) {

arr[k] = L[i];

i++;

k++;

while (j < n2) {

arr[k] = R[j];

j++;

k++;

return comparisons;

public static void printArray(int[] arr) {


//Shiv Sundar Singh
22SCSE1011854

for (int num : arr) {

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

System.out.println();

}
//Shiv Sundar Singh
22SCSE1011854

Write a program to sort the array using Quick sort and find out the best
case and worst-case scenario.
//Shiv Sundar Singh

22SCSE1011854 public class

QuickSort {

public static void main(String[] args) {

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

System.out.println("Original Array:");

printArray(arr);

quickSort(arr, 0, arr.length - 1);

System.out.println("\nSorted Array:");

printArray(arr);

int[] bestCaseArr = {11, 12, 22, 25, 34, 64, 90}; // Best-case scenario

int[] worstCaseArr = {90, 64, 34, 25, 22, 12, 11}; // Worst-case scenario

System.out.println("\nBest Case Array:");

printArray(bestCaseArr);

System.out.println("Comparisons in best case: " + quickSortWithCount(bestCaseArr, 0,


bestCaseArr.length - 1));

System.out.println("\nWorst Case Array:");

printArray(worstCaseArr);

System.out.println("Comparisons in worst case: " + quickSortWithCount(worstCaseArr, 0,


worstCaseArr.length - 1));

public static void quickSort(int[] arr, int low, int high) {

if (low < high) {

int pi = partition(arr, low, high);


//Shiv Sundar Singh
22SCSE1011854

quickSort(arr, low, pi - 1);

quickSort(arr, pi + 1, high);

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

int pivot = arr[high];

int 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;

int temp = arr[i + 1];

arr[i + 1] = arr[high];

arr[high] = temp;

return i + 1;

public static int quickSortWithCount(int[] arr, int low, int high) {

int comparisons = 0;

if (low < high) {

int pi = partitionWithCount(arr, low, high);


//Shiv Sundar Singh
22SCSE1011854

comparisons += quickSortWithCount(arr, low, pi - 1);

comparisons += quickSortWithCount(arr, pi + 1, high);

return comparisons;

public static int partitionWithCount(int[] arr, int low, int high) {

int pivot = arr[high];

int 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;

int temp = arr[i + 1];

arr[i + 1] = arr[high];

arr[high] = temp;

return i + 1;

public static void printArray(int[] arr) {

for (int num : arr) {

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

System.out.println(); }}
//Shiv Sundar Singh
22SCSE1011854

Write a program for Fibonacci series using recursive function to find the
n terms.
//Shiv Sundar Singh

22SCSE1011854 public class

Fibonacci {

public static void main(String[] args) {

int n = 10; // Number of terms in the Fibonacci series

System.out.println("Fibonacci Series up to " + n + " terms:");

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

System.out.print(fibonacciRecursive(i) + " ");

public static int fibonacciRecursive(int n) {

if (n <= 1) {

return n;

} else {

return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);

}
//Shiv Sundar Singh
22SCSE1011854

Find the Min-Max of the array.


//Shiv Sundar Singh

22SCSE1011854 public class

MinMaxArray {

public static void main(String[] args) {

int[] arr = {4, 2, 7, 1, 9, 5};

// Find min and max

int[] minMax = findMinMax(arr);

// Display min and max

System.out.println("Minimum element: " + minMax[0]);

System.out.println("Maximum element: " + minMax[1]);

public static int[] findMinMax(int[] arr) {

int min = arr[0];

int max = arr[0];

for (int i = 1; i < arr.length; i++) {

if (arr[i] < min) {

min = arr[i];

} else if (arr[i] > max) {

max = arr[i];

return new int[]{min, max};

}
//Shiv Sundar Singh
22SCSE1011854

Write a program for Tower of Hanoi using recursive function.


//Shiv Sundar Singh

22SCSE1011854 public class

TowerOfHanoi {

public static void main(String[] args) {

int n = 3; // Number of disks

char source = 'A', auxiliary = 'B', destination = 'C';

System.out.println("Tower of Hanoi with " + n + " disks:");

towerOfHanoi(n, source, auxiliary, destination);

public static void towerOfHanoi(int n, char source, char auxiliary, char destination) {

if (n == 1) {

System.out.println("Move disk 1 from " + source + " to " + destination);

return;

towerOfHanoi(n - 1, source, destination, auxiliary);

System.out.println("Move disk " + n + " from " + source + " to " + destination);

towerOfHanoi(n - 1, auxiliary, source, destination);

}
//Shiv Sundar Singh
22SCSE1011854

Find the kth minimum from the given list.


import java.util.Arrays;

//Shiv Sundar Singh

22SCSE1011854 public class

KthMinimum {

public static void main(String[] args) {

int[] arr = {4, 2, 7, 1, 9, 5};

int k = 3; // Find the 3rd minimum element

int kthMin = findKthMinimum(arr, k);

if (kthMin != Integer.MAX_VALUE) {

System.out.println("The " + k + "th minimum element is: " + kthMin);

} else {

System.out.println("There are less than " + k + " elements in the list.");

public static int findKthMinimum(int[] arr, int k) {

if (arr.length < k) {

return Integer.MAX_VALUE; // Indicates insufficient elements

Arrays.sort(arr); // Sort the array

return arr[k - 1]; // Access the kth minimum element

}
//Shiv Sundar Singh
22SCSE1011854

Find all the occurrences of a pattern in a given text. Analyse the best- and
worst-case time complexity in successful and unsuccessful search
//Shiv Sundar Singh

22SCSE1011854 public class

PatternMatching {

public static void main(String[] args) {

String text = "ababcababcabcabc";

String pattern = "abc";

System.out.println("Text: " + text);

System.out.println("Pattern: " + pattern);

findAllOccurrences(text, pattern);

public static void findAllOccurrences(String text, String pattern) {

int n = text.length();

int m = pattern.length();

int[] lps = computeLPSArray(pattern);

int i = 0; // Index for text[]

int j = 0; // Index 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)) {


//Shiv Sundar Singh
22SCSE1011854

if (j != 0) {

j = lps[j - 1];

} else {

i++;

private static int[] computeLPSArray(String pattern) {

int m = pattern.length();

int[] lps = new int[m];

int len = 0;

int i = 1;

lps[0] = 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] = len;

i++;

return lps; }}
//Shiv Sundar Singh
22SCSE1011854

Replace all the occurrences of the pattern P by pattern Q in the text T.


//Shiv Sundar Singh

22SCSE1011854 public class

PatternReplacement {

public static void main(String[] args) {

String text = "ababcababcabcabc";

String patternP = "abc";

String patternQ = "xyz";

System.out.println("Text: " + text);

System.out.println("Pattern P: " + patternP);

System.out.println("Pattern Q: " + patternQ);

String replacedText = replaceOccurrences(text, patternP, patternQ);

System.out.println("Replaced Text: " + replacedText);

public static String replaceOccurrences(String text, String patternP, String patternQ) {

int n = text.length();

int m = patternP.length();

int[] lps = computeLPSArray(patternP);

StringBuilder result = new StringBuilder();

int i = 0; // Index for text[]

int j = 0; // Index for patternP[]

while (i < n) {

if (patternP.charAt(j) == text.charAt(i)) {

i++;

j++;

}
//Shiv Sundar Singh
22SCSE1011854

if (j == m) {

// Pattern found, replace it with patternQ

result.append(patternQ);

j = lps[j - 1];

} else if (i < n && patternP.charAt(j) != text.charAt(i)) {

if (j != 0) {

j = lps[j - 1];

} else {

result.append(text.charAt(i));

i++;

// Append the remaining characters of text

while (i < n) {

result.append(text.charAt(i));

i++;

return result.toString();

private static int[] computeLPSArray(String patternP) {

int m = patternP.length();

int[] lps = new int[m];

int len = 0;

int i = 1;

lps[0] = 0;

while (i < m) {
//Shiv Sundar Singh
22SCSE1011854

if (patternP.charAt(i) == patternP.charAt(len)) {

len++;

lps[i] = len;

i++;

} else {

if (len != 0) {

len = lps[len - 1];

} else {

lps[i] = len;

i++;

return lps;

}
//Shiv Sundar Singh
22SCSE1011854

I have to multiply matrices A1A2..Aj..An. Design a method to find the best


way to multiply all these matrices so that the time taken to multiply can
be minimized.
//Shiv Sundar Singh 22SCSE1011854

public class MatrixChainMultiplication {

public static void main(String[] args) {

int[] dimensions = {10, 30, 5, 60}; // Dimensions of matrices A1, A2, ..., An

// Calculate the minimum number of scalar multiplications needed

int minScalarMultiplications = findOptimalMultiplications(dimensions);

System.out.println("Minimum number of scalar multiplications needed: " +


minScalarMultiplications);

public static int findOptimalMultiplications(int[] dimensions) {

int n = dimensions.length - 1; // Number of matrices

int[][] dp = new int[n][n];

// Initialize dp array with -1

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

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

dp[i][j] = -1;

return matrixChainOrder(dimensions, 1, n - 1, dp);

private static int matrixChainOrder(int[] dimensions, int i, int j, int[][] dp) {

if (i == j) {
//Shiv Sundar Singh
22SCSE1011854

return 0;

if (dp[i][j] != -1) {

return dp[i][j];

dp[i][j] = Integer.MAX_VALUE;

for (int k = i; k < j; k++) {

int cost = matrixChainOrder(dimensions, i, k, dp) +

matrixChainOrder(dimensions, k + 1, j, dp) +

dimensions[i - 1] * dimensions[k] * dimensions[j];

dp[i][j] = Math.min(dp[i][j], cost);

return dp[i][j];

}
//Shiv Sundar Singh
22SCSE1011854

Write a program to multiply two decimal integer numbers using divide and
conquer method.

//Shiv Sundar Singh 22SCSE1011854

public class DecimalMultiplication {

public static void main(String[] args) {

int num1 = 1234;

int num2 = 5678;

long result = multiply(num1, num2);

System.out.println("Product: " + result);

public static long multiply(int num1, int num2) {

String strNum1 = Integer.toString(num1);

String strNum2 = Integer.toString(num2);

int n = Math.max(strNum1.length(), strNum2.length());

if (n == 1) {

return num1 * num2;

// Splitting into halves

int m = n / 2;

// Divide

int a = Integer.parseInt(strNum1.substring(0, strNum1.length() - m));

int b = Integer.parseInt(strNum1.substring(strNum1.length() - m));

int c = Integer.parseInt(strNum2.substring(0, strNum2.length() - m));


//Shiv Sundar Singh
22SCSE1011854

int d = Integer.parseInt(strNum2.substring(strNum2.length() - m));

// Conquer

long ac = multiply(a, c);

long bd = multiply(b, d);

long ad_plus_bc = multiply(a + b, c + d) - ac - bd;

// Combine

return (long) (ac * Math.pow(10, 2 * m) + ad_plus_bc * Math.pow(10, m) + bd);

}
//Shiv Sundar Singh
22SCSE1011854

Write a program to find the minimum sum of lengths between the nodes
of the undirected connected graph using two different methods.
//Shiv Sundar Singh 22SCSE1011854

// Implementation of Floyd-Warshall Algorithm

public class FloydWarshallAlgorithm {

// Function to find the minimum sum of lengths between the nodes of the undirected connected
graph

public static int minimumSumOfLengths(int[][] graph) {

int n = graph.length;

int minSum = Integer.MAX_VALUE;

int[][] dist = new int[n][n];

// Initialize distances

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

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

dist[i][j] = (i == j) ? 0 : (graph[i][j] == 0 ? Integer.MAX_VALUE : graph[i][j]);

// Floyd-Warshall Algorithm

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

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

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

if (dist[i][k] != Integer.MAX_VALUE && dist[k][j] != Integer.MAX_VALUE) {

dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);

}
//Shiv Sundar Singh
22SCSE1011854

// Sum the lengths of the shortest paths

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

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

if (dist[i][j] != Integer.MAX_VALUE) {

minSum = Math.min(minSum, dist[i][j]);

return minSum;

}
//Shiv Sundar Singh
22SCSE1011854

Problem: You are a delivery driver with a limited capacity truck. Your goal
is to maximize your earnings by delivering packages to various locations.
Each package has a weight and a profit associated with it. However, you
can only deliver packages whose total weight does not exceed your truck's
capacity. How can you choose which packages to deliver to maximize your
earnings?
Your truck can carry a maximum weight of 50 units. You have the
following packages available for delivery:

Package 1: Weight = 20 units, Profit = ₹100


Package 2: Weight = 30 units, Profit = ₹120
Package 3: Weight = 15 units, Profit = ₹60
Package 4: Weight = 10 units, Profit = ₹45

What is the maximum profit you can earn by delivering packages


within your truck's capacity?
//Shiv Sundar Singh

22SCSE1011854 public class

KnapsackProblem {

public static void main(String[] args) {

int[] weights = {20, 30, 15, 10};

int[] profits = {100, 120, 60, 45};

int capacity = 50;

int maxProfit = knapsack(weights, profits, capacity);

System.out.println("Maximum profit: ₹" + maxProfit);

public static int knapsack(int[] weights, int[] profits, int capacity) {

int n = weights.length;

int[][] dp = new int[n + 1][capacity + 1];

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

for (int j = 1; j <= capacity; j++) {


//Shiv Sundar Singh
22SCSE1011854

if (weights[i - 1] <= j) {

dp[i][j] = Math.max(profits[i - 1] + dp[i - 1][j - weights[i - 1]], dp[i - 1][j]);

} else {

dp[i][j] = dp[i - 1][j];

return dp[n][capacity];

}
//Shiv Sundar Singh
22SCSE1011854

In the field of bioinformatics, analysing the genetic sequences of


organisms is crucial for understanding evolutionary relationships and
genetic diseases. Scientists often need to compare DNA sequences to
identify regions of similarity that may suggest a shared evolutionary
history or common functionalities.

The DNA sequences are represented as strings composed of the


characters 'A', 'C', 'G', and 'T', which stand for the four nucleotide bases
of a DNA strand: adenine, cytosine, guanine, and thymine. Your task is
to design an algorithm that can compare two DNA sequences of a
“Man” with “Monkey” and find the maximum length common
sequence of DNA.

Example:
- Input:
Sequence 1: "ACGTAC"
Sequence 2: "TACGAC"
- Output: "ACAC"

//Shiv Sundar Singh 22SCSE1011854

import java.util.*;

public class DNASequenceAnalysis {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

String sequence1=sc.next();

String sequence2=sc.next();

String lcs = flc(sequence1, sequence2);

System.out.println("OUTPUT: " + lcs);

public static String flc(String s1, String s2) {


//Shiv Sundar Singh
22SCSE1011854

int m = s1.length();

int t = s2.length();

int[][] dp = new int[m + 1][t + 1];

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

for (int j = 1; j <= t; j++) {

if (s1.charAt(i - 1) == s2.charAt(j - 1)) {

dp[i][j] = dp[i - 1][j - 1] + 1;

} else {

dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);

StringBuilder lcs = new StringBuilder();

int i = m, j = t;

while (i > 0 && j > 0) {

if (s1.charAt(i - 1) == s2.charAt(j - 1)) {

lcs.append(s1.charAt(i - 1));

i--;

j--;

} else if (dp[i - 1][j] > dp[i][j - 1]) {

i--;

} else {

j--;

return lcs.reverse().toString();

}
//Shiv Sundar Singh
22SCSE1011854

You might also like