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

Design and Analysis of Algorithms Lab Manual

Design nhsjxmx sbjsK

Uploaded by

21be02050
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Design and Analysis of Algorithms Lab Manual

Design nhsjxmx sbjsK

Uploaded by

21be02050
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Design and analysis of algorithms lab manual

Program-1:
(1)Write a java program to implement Merge sort algorithm for sorting a list of integers in
ascending order.

Program code:
import java.util.Arrays;

public class MergeSort {

public static void main(String[] args) {

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

System.out.println("Original Array: " + Arrays.toString(array));

mergeSort(array, 0, array.length - 1);//Sorting the array

System.out.println("Sorted Array: " + Arrays.toString(array));

public static void mergeSort(int[] array, int left, int right) {//

if (left < right) {

int mid = (left + right) / 2;

mergeSort(array, left, mid);

mergeSort(array, mid + 1, right);

merge(array, left, mid, right);

public static void merge(int[] array, int left, int mid, int right) {

int n1 = mid - left + 1;

int n2 = right - mid;

int[] L = new int[n1];

int[] R = new int[n2];

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

L[i] = array[left + i];


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

R[j] = array[mid + 1 + j];

int i = 0, j = 0;

int k = left;

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

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

array[k] = L[i];

i++;

} else {

array[k] = R[j];

j++;

k++;

while (i < n1) {

array[k] = L[i];

i++;

k++;

while (j < n2) {

array[k] = R[j];

j++;

k++;

Output: Original Array: [12, 11, 13, 5, 6, 7]

Sorted Array: [5, 6, 7, 11, 12, 13]


Program(2):
(2)Write a java program to implement the backtracking algorithm for the sum of subsets problem.

Program code:

import java.util.ArrayList;
import java.util.List;
public class SubsetSum {
public static void main(String[] args) {
int[] nums = {10, 7, 5, 18, 12, 20, 15};
int targetSum = 35;
System.out.println("Original Array: ");
for (int num : nums) {
System.out.print(num + " ");
}
System.out.println("\n\nSubsets with sum " + targetSum + ": ");
List<List<Integer>> subsets = findSubsets(nums, targetSum);
for (List<Integer> subset : subsets) {
System.out.println(subset);
}
}
public static List<List<Integer>> findSubsets(int[] nums, int targetSum) {
List<List<Integer>> result = new ArrayList<>();
backtrack(result, new ArrayList<>(), nums, targetSum, 0);
return result;
}
private static void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] nums,
int remain, int start) {
if (remain < 0) return;
else if (remain == 0) result.add(new ArrayList<>(tempList));
else {
for (int i = start; i < nums.length; i++) {
tempList.add(nums[i]);
backtrack(result, tempList, nums, remain - nums[i], i + 1);
tempList.remove(tempList.size() - 1);
}
}
}
}
Output:
Original Array:
10 7 5 18 12 20 15
Subsets with sum 35:
[10, 7, 18]
[10, 5, 20]
[5, 18, 12]
[20, 15]

Program(3):
(3)Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and
Display() methods to demonstrate its working.

Program Code:

public class ArrayStack {


private int maxSize; // Maximum size of the stack
private int[] stackArray; // Array to hold the stack elements
private int top; // Index of the top element in the stack
// Constructor to initialize the stack
public ArrayStack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1; // Stack is initially empty
}
// Method to push an element onto the stack
public void push(int element) {
if (isFull()) {
System.out.println("Stack is full. Cannot push element " + element);
return;
}
stackArray[++top] = element;
System.out.println("Pushed element " + element + " onto the stack");
}
// Method to pop an element from the stack
public int pop() {
if (isEmpty()) {
System.out.println("Stack is empty. Cannot pop element.");
return -1; // Return -1 to indicate stack underflow
}
int poppedElement = stackArray[top--];
System.out.println("Popped element " + poppedElement + " from the stack");
return poppedElement;
}
// Method to display elements of the stack
public void display() {
if (isEmpty()) {
System.out.println("Stack is empty.");
return;
}
System.out.println("Elements in the stack:");
for (int i = top; i >= 0; i--) {
System.out.println(stackArray[i]);
}
}
// Helper method to check if the stack is full
private boolean isFull() {
return (top == maxSize - 1);
}
// Helper method to check if the stack is empty
private boolean isEmpty() {
return (top == -1);
}
public static void main(String[] args) {
// Create a stack with a maximum size of 5
ArrayStack stack = new ArrayStack(5);
// Push elements onto the stack
stack.push(10);
stack.push(20);
stack.push(30);
// Display elements of the stack
stack.display();
// Pop an element from the stack
stack.pop();
// Display elements of the stack after popping
stack.display();
}}
Output:
Pushed element 10 onto the stack
Pushed element 20 onto the stack
Pushed element 30 onto the stack
Elements in the stack:
30
20
10
Popped element 30 from the stack
Elements in the stack:
20
10

Program(4):
(4) Write a Java class called Customer to store their name and date_of_birth. The date_of_birth
format should be dd/mm/yyyy. Write methods to read customer data as and display as
usingStringTokenizer classconsideringthedelimiter characteras.

Program Code:
import java.util.Scanner;
import java.util.StringTokenizer;
class Customer
{
private String customerName,date;
public Customer(String customerName, String date)
{
super();
this.customerName = customerName;
this.date = date;
}
@Override
public String toString()
{
String returnValue = customerName+",";
StringTokenizer tokenizer = new StringTokenizer(date,"/");
System.out.println("The Customer details are ");
while(tokenizer.hasMoreTokens())
{
returnValue = returnValue+tokenizer.nextToken();
if(tokenizer.hasMoreElements())
{
returnValue = returnValue+",";
}
}
return returnValue;
}
}
public class CustomerDetails
{
public static void main(String[] args)
{
String customerName;
String date;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter customer name");
customerName = scanner.next();
System.out.println("Enter Date (dd/mm/yyy)");
date = scanner.next();
Customer customer = new Customer(customerName,date);
System.out.println(customer.toString());
}
}
Out put:
Enter customer name
mani
Enter Date (dd/mm/yyy)
03/03/2001
The Customer details are
mani,03,03,2001

Program(5)
(5) Write a Java program to read two integers a and b. Compute a/b and print, when b is not zero.
Raise an exception when b is equal to zero.

Program Code:

import java.util.*;
public class Division
{
public static void main(String[] args)
{
int a,b,quotient;
Scanner s = new Scanner(System.in);
System.out.println("Enter Numerator:" );
a = s.nextInt();
System.out.println("Enter Denominator:" );
b = s.nextInt();
try
{
quotient=a/b;
System.out.println("Quotient=" + quotient);
}
catch(ArithmeticException ae)
{
System.out.println(ae);
}
}
}
Output: output:
Enter Numerator: Enter Numerator:
100 50
Enter Denominator: Enter Denominator:
50 0
Quotient=2 java.lang.ArithmeticException: / by zero

Program(6):
(6) Design and implement in Java to find a sub set of a given set S = {Sl,S2,.....,Sn} of n positive
integers whose SUM is equal to a given positive integer d. For example, if S ={1, 2, 5, 6, 8} and d= 9,
there are two solutions {1,2,6}and {1,8}. Display a suitable message, if the given problem instance
doesn't have a solution.

Program Code:

import java.util.ArrayList;

import java.util.List;

public class SubsetSum {

public static void main(String[] args) {

int[] set = {1, 2, 5, 6, 8};

int d = 9;

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

for (int num : set) {

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

System.out.println("\n\nSubsets with sum " + d + ": ");

List<List<Integer>> subsets = findSubsetsWithSum(set, d);

if (subsets.isEmpty()) {

System.out.println("No subset found with sum " + d);

} else {

for (List<Integer> subset : subsets) {

System.out.println(subset);

}
}

public static List<List<Integer>> findSubsetsWithSum(int[] set, int d) {

List<List<Integer>> result = new ArrayList<>();

backtrack(result, new ArrayList<>(), set, d, 0);

return result;

private static void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] set, int remain,
int start) {

if (remain < 0) return;

else if (remain == 0) result.add(new ArrayList<>(tempList));

else {

for (int i = start; i < set.length; i++) {

tempList.add(set[i]);

backtrack(result, tempList, set, remain - set[i], i + 1);

tempList.remove(tempList.size() - 1);

Output:

Original Set:

12568

Subsets with sum 9:

[1, 2, 6]

[1, 8]

Program(7):
(7)Write a java program to implement binary search algorithm with programmer inputs.
Program code:
import java.util.Scanner;
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
return -1;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
int[] arr = new int[size];
System.out.println("Enter the elements of the array in sorted order:");
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}
System.out.print("Enter the number to search: ");
int target = scanner.nextInt();
int index = binarySearch(arr, target);
if (index != -1) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found in the array.");
}
scanner.close();
}
}
Output:
Enter the size of the array: 5
Enter the elements of the array in sorted order:
10
20
30
40
50
Enter the number to search: 40
Element found at index :3

Program(8):
(8)Write a java program to find third largest element in an array?With programmer inputs.
Program Code:
import java.util.Scanner;

public class ThirdLargest {

public static int thirdLargest(int[] arr) {


I nt n = arr.length;
if (n < 3) {
System.out.println("Array size should be at least 3");
return -1;
}

int first = arr[0];


int second = Integer.MIN_VALUE;
int third = Integer.MIN_VALUE;

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


if (arr[i] > first) {
third = second;
second = first;
first = arr[i];
} else if (arr[i] > second) {
third = second;
second = arr[i];
} else if (arr[i] > third) {
third = arr[i];
}
}
return third;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
int[] arr = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}
int thirdLargest = thirdLargest(arr);
if (thirdLargest != -1) {
System.out.println("The third largest number in the array is: " + thirdLargest);
}
scanner.close();
}
}

Output:
Enter the size of the array: 5
Enter the elements of the array:
23
34
56
45
67
The third largest number in the array is: 45
Program(9):
(9)Write a java program to reverse of a string with programmer inputs?
Program code:
import java.util.Scanner;

public class ReverseString {

public static String reverseString(String str) {


// Convert the string to a character array
char[] charArray = str.toCharArray();

// Define pointers for the start and end of the string


int start = 0;
int end = str.length() - 1;

// Reverse the characters in the character array


while (start < end) {
// Swap characters at start and end positions
char temp = charArray[start];
charArray[start] = charArray[end];
charArray[end] = temp;

// Move pointers towards the center


start++;
end--;
}

// Convert the character array back to a string


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

System.out.print("Enter a string: ");


String inputString = scanner.nextLine();

// Reverse the input string


String reversedString = reverseString(inputString);

// Print the reversed string


System.out.println("Reversed string: " + reversedString);

scanner.close();
}
}
Output:
Enter a string: 12345
Reversed string: 54321

Program(10)
(10)Write a java program to implement Fibonacci series in java using recursion.
Program code:
import java.util.Scanner;

public class FibonacciSeries {

// Recursive method to calculate Fibonacci numbers


public static int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
// Fibonacci series is sum of previous two Fibonacci numbers
return fibonacci(n - 1) + fibonacci(n - 2);
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of terms in the Fibonacci series: ");


int numTerms = scanner.nextInt();

System.out.println("Fibonacci series:");
for (int i = 0; i < numTerms; i++) {
System.out.print(fibonacci(i) + " ");
}

scanner.close();
}
}
Output:
Enter the number of terms in the Fibonacci series: 10
Fibonacci series:
0 1 1 2 3 5 8 13 21 34

You might also like