0% found this document useful (0 votes)
7 views63 pages

Algorithms Manual (1)

The document provides instructions and guidelines for students in an algorithm laboratory course, including rules for laboratory conduct and a list of experiments to be performed using Java programming. The course aims to develop software skills, understand algorithm concepts, and apply various programming techniques. Additionally, it outlines specific experiments involving searching and sorting algorithms, graph traversal, and optimization problems, along with expected outcomes and lab requirements.
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)
7 views63 pages

Algorithms Manual (1)

The document provides instructions and guidelines for students in an algorithm laboratory course, including rules for laboratory conduct and a list of experiments to be performed using Java programming. The course aims to develop software skills, understand algorithm concepts, and apply various programming techniques. Additionally, it outlines specific experiments involving searching and sorting algorithms, graph traversal, and optimization problems, along with expected outcomes and lab requirements.
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/ 63

INSTRUCTION TO THE STUDENTS

 Students should not wear foot wares inside the laboratory.

 Students should enter his/her name, system number and in time while entering into the
laboratory.

 Students should submit his/her observation note before they start working in the system.

 After completing the experiments, verification of the program should be obtained from
the concern staff in-charges.

 Students should arrange the chair and the system in a proper manner, and they should
enter the out time in the lab register.

COURSE OBJECTIVES:

 To build software development skills using java programming for real-world applications.
 To understand and apply the concepts of classes, packages, interfaces, inheritance,
exception handling and file processing.
 To develop applications using generic programming and event handling

LIST OF EXPERIMENTS:

1. Implement Linear Search. Determine the time required to search for an element.
Repeat the experiment for different values of n, the number of elements in the list to be
searched and plot a graph of the time taken versus n.

2. Implement recursive Binary Search. Determine the time required to search an element.
Repeat the experiment for different values of n, the number of elements in the list to be
searched and plot a graph of the time taken versus n.

3. Given a text txt [0...n-1] and a pattern pat [0...m-1], write a function search (char pat [ ],
char txt [ ]) that prints all occurrences of pat [ ] in txt [ ]. You may assume that n > m.

4. Sort a given set of elements using the Insertion sort and Heap sort methods and
determine the time required to sort the elements. Repeat the experiment for different
values of n, the number of elements in the list to be sorted and plot a graph of the time
taken versus n.
5. Develop a program to implement graph traversal using Breadth First Search

6. Develop a program to implement graph traversal using Depth First Search

7. From a given vertex in a weighted connected graph, develop a program to find the
shortest paths to other vertices using Dijkstra’s algorithm.

8. Find the minimum cost spanning tree of a given undirected graph using Prim’s
algorithm.

9. Implement Floyd’s algorithm for the All-Pairs- Shortest-Paths problem.

10. Compute the transitive closure of a given directed graph using Warshall's algorithm.

11. Develop a program to find out the maximum and minimum numbers in a given list of
n numbers using the divide and conquer technique.

12. Implement Merge sort and Quick sort methods to sort an array of elements and
determine the time required to sort. Repeat the experiment for different values of n, the
number of elements in the list to be sorted and plot a graph of the time taken versus n.
State Space Search Algorithms

13. Implement N Queens problem using Backtracking.

14. Implement any scheme to find the optimal solution for the Traveling Salesperson
problem and then solve the same problem instance using any approximation algorithm
and determine the error in the approximation.

15. Implement randomized algorithms for finding the kth smallest number. The
programs can be implemented in C/C++/JAVA/ Python.

Lab Requirements:

 Operating Systems: Linux / Windows


 Front End Tools: Eclipse IDE / Netbeans IDE
CS3401 – ALGORITHM LABORATORY

LIST OF EXPERIMENTS:

1. Implement Linear Search. Determine the time required to search for an element.
Repeat the experiment for different values of n, the number of elements in the list to be
searched and plot a graph of the time taken versus n.

2. Implement recursive Binary Search. Determine the time required to search an element.
Repeat the experiment for different values of n, the number of elements in the list to be
searched and plot a graph of the time taken versus n.

3. Given a text txt [0...n-1] and a pattern pat [0...m-1], write a function search (char pat [ ],
char txt [ ]) that prints all occurrences of pat [ ] in txt [ ]. You may assume that n > m.

4. Sort a given set of elements using the Insertion sort and Heap sort methods and
determine the time required to sort the elements. Repeat the experiment for different
values of n, the number of elements in the list to be sorted and plot a graph of the time
taken versus n.

5. Develop a program to implement graph traversal using Breadth First Search

6. Develop a program to implement graph traversal using Depth First Search

7. From a given vertex in a weighted connected graph, develop a program to find the
shortest paths to other vertices using Dijkstra’s algorithm.

8. Find the minimum cost spanning tree of a given undirected graph using Prim’s
algorithm.

9. Implement Floyd’s algorithm for the All-Pairs- Shortest-Paths problem.

10. Compute the transitive closure of a given directed graph using Warshall's algorithm.

11. Develop a program to find out the maximum and minimum numbers in a given list of
n numbers using the divide and conquer technique.
12. Implement Merge sort and Quick sort methods to sort an array of elements and
determine the time required to sort. Repeat the experiment for different values of n, the
number of elements in the list to be sorted and plot a graph of the time taken versus n.
State Space Search Algorithms

13.Implement N Queens problem using Backtracking.

14. Implement any scheme to find the optimal solution for the Traveling Salesperson
problem and then solve the same problem instance using any approximation algorithm
anddetermine the error in the approximation.

15. Implement randomized algorithms for finding the kth smallest number. The programs
can be implemented in C/C++/JAVA/ Python.

CO COURSE OUTCOME K
At the end of the course student will be able to LEVEL
CO1 Analyze the efficiency of algorithms using various frameworks K3
CO2 Apply graph algorithms to solve problems and analyze their efficiency. K3
Make use of algorithm design techniques like divide and conquer, dynamic
CO3 programming and greedy techniques to solve problems K3

CO4 Use the state space tree method for solving problems. K6
CO5 Solve problems using approximation algorithms and randomized algorithms K3
CS3401- ALGORITHM LABORATORY

Table of Contents

S.NO DATE NAME OF THE EXPERIMENT PAGE.NO MARKS SIGN

1 Implementation of Linear Search.

2 Implementation of Recursive Binary Search.

3 Implementation of Pattern Search.

4 Implementation of Insertion sort and Heap sort.

5 Implementation of graph traversal using Breadth


First Search
6 Implementation of graph traversal using
Depth First Search

7 Implementation of Dijkstra’s algorithm.

8 Implementation of Prim’s algorithm.

9 Implementation of Floyds algorithm.

10 Implementation of Warshall's algorithm

11 Develop an application using the divide and


conquer
technique.
12 Implement Quick sort and Merge sort

13 Implement N Queens problem using


Backtracking.
14 Develop an application using approximation
algorithm

15. Implementation of randomized algorithms


Ex.No. 1A Implementation of Linear Search
Date :

AIM :

To write a java program for Implementation of Linear Search in array

ALGORITHM :

1. Start by defining a function called linear_search_array that takes in two parameters: an array of
elements and the element to be searched.
2. Loop through each element in the array using a for loop.
3. Check if the current element is equal to the element to be searched. If true, return the index of the
element.
4. If the element is not found in the array, return -1.

PROGRAM :

import java.util.Scanner;
class Example2
{
public static void main(String args[])
{
int i,len, key, array[];
Scanner input = new Scanner(System.in);
System.out.println("Enter Array length:");
len = input.nextInt();
array = new int[len];
System.out.println("Enter " + len + " elements");
for (i = 0; i < len; i++)
{
array[i] = input.nextInt();
}
System.out.println("Enter the search key value:");
key = input.nextInt();
for (i = 0; i < len; i++)
{
if (array[i]== key)
{
System.out.println(key+" is present at location "+(i+1));
break;
}
}
if (i == len)
System.out.println(key + " doesn't exist in array.");
}
}
OTUPUT :

Enter Array Length : 9

Enter a Elements :
5 4 3 2 1 0 11 7 9

Enter the Sarch key Value : 1

1 is found at location 5

RESULT :

Thus the program linear search in array was executed successfullY


Ex.No. 1B Implementation of Linear Search
Date :

AIM :

To write a java program for Implementation of Linear Search in Recursion

ALGORITHM :

1. Define a function named linear_search_recursion that takes in three parameters: an array of


elements, the element to be searched, and the length of the array.
2. Check if the length of the array is zero or less than zero. If true, return -1 indicating that the
element is not found in the array.
3. Check if the first element of the array is equal to the element to be searched. If true, return the
index of the element.
4. Call the linear_search_recursion function recursively with the array sliced from index 1 to the end,
the element to be searched, and the length of the array minus 1.
5. If the element is not found in the sliced array, return -1.

PROGRAM :

import java.util.Scanner;
class RecursionExample3
{
int recursionSearch(int arr[], int start, int last, int x)
{
if (last < start)
return -1;
if (arr[start] == x)
return start;
return recursionSearch(arr, start+1, last, x);
}
public static void main(String args[])
{
RecursionExample3 ref=new RecursionExample3();
int i,len, key, array[];
Scanner input = new Scanner(System.in);
System.out.println("Enter Array length:");
len = input.nextInt();
array = new int[len];
System.out.println("Enter " + len + " elements");
for (i = 0; i < len; i++)
{
array[i] = input.nextInt();
}
System.out.println("Enter the search key value:");
key = input.nextInt()
int index=ref.recursionSearch(array,0,len-1,key);
if (index!=-1)
{
System.out.println(key+" is found at location "+(index+1));
}
else
{
System.out.println(key + " doesn't exist in array.");
}
}
}
OUTPUT :

Enter Array Length : 9

Enter a Elements :

5 4 3 2 11 0 1 7 9

Enter the Sarch key Value : 11

11 is present at location 5

RESULT :

Thus the program linear search in recursion was executed successfully


Ex.No. 2A Implementation of Binary Search
Date :

AIM :

To write a java program for Implementation of Binary Search in Array

ALGORITHM :

1. Start by defining a function called binary_search_array that takes in two parameters: an array of
elements and the element to be searched.
2. Initialize two variables, low and high, to the first and last indices of the array respectively
3. Loop through the array while low is less than or equal to high.
4. Calculate the middle index as (low + high) // 2.
5. Check if the element at the middle index is equal to the element to be searched. If true, return
the middle index.
6. If the element at the middle index is greater than the element to be searched, update high to be
one less than the middle index
7. If the element at the middle index is less than the element to be searched, update low to be one
more than the middle index.
8. If the element is not found in the array, return -1.

PROGRAM :

import java.util.Scanner;
class Main {
int binarySearch(int array[], int element, int low, int high)
{while (low <= high) {
int mid = low + (high - low) / 2;
// if element to be searched is the mid element
if (array[mid] == element)
return mid;
// if element is less than mid element
// search only the left side of mid
if (array[mid] < element)
low = mid + 1;
// if element is greater than mid element
// search only the right side of mid
else
high = mid - 1;
}
return -1;
}
public static void main(String args[]) {
// create an object of Main class
Main obj = new Main();
// create a sorted array
int[] array = { 3, 4, 5, 6, 7, 8, 9 };
int n = array.length;
// get input from user for element to be searched
Scanner input = new Scanner(System.in);
System.out.println("Enter element to be searched:");
// element to be searched
int element = input.nextInt();
input.close();
// call the binary search method
// pass arguments: array, element, index of first and last element
int result = obj.binarySearch(array, element, 0, n - 1);
if (result == -1)
System.out.println("Not found");
else
System.out.println("Element found at index " + result);
}
}
OUTPUT :

Enter a element to be searched

Elemeny found at location 2

RESULT :

Thus the program binary search in array was executed successfully


Ex.No. 2B Implementation of Binary Search
Date :

AIM :

To write a java program for Implementation of Binary Search in Recursion

ALGORITHM :

1. Start by defining a function called binary_search_recursion that takes in three parameters: an


array of elements, the element to be searched, and the starting and ending indices of the array.
2. Check if the starting index is less than or equal to the ending index.
3. Calculate the middle index as (start + end) // 2.
4. Check if the element at the middle index is equal to the element to be searched. If true, return
the middle index.
5. If the element at the middle index is greater than the element to be searched, recursively call the
binary_search_recursion function with the same array, element, and starting index, but with the
ending index set to one less than the middle index.
6. If the element at the middle index is less than the element to be searched, recursively call the
binary_search_recursion function with the same array, element, and ending index, but with the
starting index set to one more than the middle index.
7. If the element is not found in the array, return -1.

PROGRAM :

import java.util.Scanner;
public class BinarySearchRecursive
{ public static void main(String[] args)
{
Scanner commandReader = new Scanner(System.in);
System.out.println("Welcome to Java Program to perform
binary search on int array");
System.out.println("Enter total number of elements : ");
int length = commandReader.nextInt();
int[] input = new int[length];
System.out.printf("Enter %d integers %n", length);
for (int i = 0; i < length; i++) {
input[i] = commandReader.nextInt();
}
System.outprintln("Please enter number to be searchedin array (sorted order)");int key =
commandReader.nextInt();
if (index == -1) {
System.out.printf("Sorry, %d is not found in array %n", key);
} else {
System.out.printf("%d is found in array at index %d %n", key, index);
}

commandReader.close();
}
public static int recursiveBinarySearch(int[] input, int key)
{return binarySearch(input, 0, input.length - 1, key);
}
private static int binarySearch(int[] array, int start, int end, int target)
{int middle = (start + end) / 2;
if (end < start)
{return -1;
}
if (target == array[middle])
{return middle;
} else if (target < array[middle]) {
return binarySearch(array, start, middle - 1, target);
} else {
return binarySearch(array, middle + 1, end, target);
}
}
}
OUTPUT :

Welcome to java program to perform a binary search on int array

Enter total number of element

Enter 5 integer

12367

Please Enter number to be searched in array sorted order

6 is found in array at indexed 3

RESULT :

Thus the program binary search in recursion was executed successfully


Ex.No. 3 Implementation of Pattern Search
Date :

AIM :

To write a java program for Implementation of Pattern Search.

ALGORITHM :

1. Start by defining a function called naive_algorithm that takes in two parameters: an array of
elements and the element to be searched.
2. Loop through each element in the array.
3. Check if the current element is equal to the element to be searched. If true, return the index of the
current element.
4. If the element is not found in the array, return -1.

PROGRAM :

// Java program for Naive Pattern Searching


public class NaiveSearch {
public static void search(String txt, String pat)
{
int M = pat.length();
int N = txt.length();

/* A loop to slide pat one by one */


for (int i = 0; i <= N - M; i++) {

int j
/* For current index i, check for pattern
match */
for (j = 0; j < M; j++)
if (txt.charAt(i + j) != pat.charAt(j))
break;

if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1]


System.out.println("Pattern found at index " + i);
}
}

public static void main(String[] args)


{
String txt = "AABAACAADAABAAABAA";
String pat = "AABA";
search(txt, pat);
}
}
OUTPUT :

Pattern found at location 0

Pattern found at location 0

Pattern found at location 9

Pattern found at location

RESULT :

Thus the program Pattern Search was executed successfully.


Ex.No. 4A Implementation of Insertion sort
Date :

AIM :

To write a java program for Implementation of Insertion sort

ALGORITHM :

1. Start by defining a function called insertion_sort that takes in an array of elements as a parameter.
2. Loop through each element in the array, starting from the second element.
3. Compare the current element with the previous element. If the current element is smaller, then
swap them.
4. Continue comparing and swapping the current element with the previous element until the current
element is in its correct position.
5. Repeat steps 2-4 for all elements in the array.

PROGRAM :

import java.util.*;
public class Main {
public static void main(String[] args) {
//declare an array and print the original contents
int[] numArray = {10,6,15,4,1,45};
System.out.println("Original Array:" + Arrays.toString(numArray));
//apply insertion sort algorithm on the array
for(int k=1; k<numArray.length-1; k++) {
int temp = numArray[k];
int j= k-1;
while(j>=0 && temp <= numArray[j])
{numArray[j+1] = numArray[j];
j = j-1;
}
numArray[j+1] = temp;
}
//print the sorted array
System.out.println("Sorted Array:" + Arrays.toString(numArray));
}
}
OUTPUT :

Original Array : [10,6,15,4,1,45]

Sorted Array : [1,4,6,10,15,45]

RESULT :

Thus the program Insertion Sort was executed successfully


Ex.No. 4B Implementation of Heap sort
Date :

AIM :

To write a java program for Implementation of Heap sort

ALGORITHM :

1. Start by defining a function called heap_sort that takes in an array of elements as a parameter.
2. Convert the array into a max heap by using a heapify function. This involves comparing each parent node
with its children and swapping them if necessary to ensure that the parent node is greater than both of its
children.
3. Once the array has been converted into a max heap, swap the root node (which is the largest element) with
the last element in the array.
4. Remove the last element from the array (which is now the largest element) and add it to a sorted list.
5. Repeat steps 2-4 for the remaining elements in the array, until all elements have been added to the sorted
list.

PROGRAM :

import java.util.Scanner;
public class HeapSort{
private static int N;
public static void sort(int arr[]){
heapMethod(arr);
for (int i = N; i > 0; i--){
swap(arr,0, i);
N = N-1;
heap(arr, 0);
}
}
public static void heapMethod(int
arr[]){N = arr.length-1;
for (int i = N/2; i >= 0; i--)
heap(arr, i);
}
public static void heap(int arr[], int
i){int left = 2*i ;
int right = 2*i + 1;
int max = i;
if (left <= N && arr[left] > arr[i])
max = left;
if (right <= N && arr[right] > arr[max])
max = right;
if (max != i){
swap(arr, i, max);
heap(arr, max);
}
}
public static void swap(int arr[], int i, int
j){int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static void main(String[] args)
{ Scanner in = new
Scanner( System.in );int n;
System.out.println("Enter the number of elements to be sorted:");
n = in.nextInt();
int arr[] = new int[ n ];
System.out.println("Enter "+ n +" integer elements");
for (int i = 0; i < n; i++)
arr[i] = in.nextInt();
sort(arr);
System.out.println("After sorting ");
for (int i = 0; i < n; i++)
System.out.println(arr[i]+" ");
System.out.println();
}
}
OUTPUT :

Enter the number of elements to be sorted:


7

Enter 7 integer elements

3 66 70 53 22 90 100

After sorting 3

22

53

66

70

90

100

RESULT :

Thus the program Heap Sort was executed successfully


Ex.No. 5 Implementation of graph traversal using Breadth First Search
Date :

AIM :

To write a java program for Implementation of graph traversal using Breadth First Search

ALGORITHM :

1. Create a queue data structure.


2. Add the starting node to the queue.
3. Mark the starting node as visited.
4. While the queue is not empty, do the following:
a. Remove the first node from the queue.
b. For each unvisited neighbor of the current node, do the following:
i. Mark the neighbor as visited.
ii. Add the neighbor to the end of the queue.
5. Repeat steps 4 and 5 until the queue is empty.

PROGRAM :

import java.io.*;
import java.util.*;
public class BFSTraversal
{
private int node;
private LinkedList<Integer> adj[];
private Queue<Integer> que;
BFSTraversal(int v)
{
node = v;
adj = new LinkedList[node];
for (int i=0; i<v; i++)
{
adj[i] = new LinkedList<>();
}
que = new LinkedList<Integer>();
}
void insertEdge(int v,int w)

{adj[v].add(w);

}
void BFS(int n)
{
boolean nodes[] = new boolean[node];
int a = 0;
nodes[n]=true;
que.add(n);
while (que.size() != 0)
{
n = que.poll();
System.out.print(n+" ");
for (int i = 0; i < adj[n].size(); i++)
{
a = adj[n].get(i);
if (!nodes[a])
{
nodes[a] = true;
que.add(a);
}
}
}
}
public static void main(String args[])
{
BFSTraversal graph = new BFSTraversal(6);
graph.insertEdge(0, 1);

graph.insertEdge(0, 3);

graph.insertEdge(0, 4);

graph.insertEdge(4, 5);

graph.insertEdge(3, 5);

graph.insertEdge(1, 2);

graph.insertEdge(1, 0);

graph.insertEdge(2, 1);

graph.insertEdge(4, 1);

graph.insertEdge(3, 1);

graph.insertEdge(5, 4);

graph.insertEdge(5, 3);
System.out.println("Breadth First Traversal for the graph is:");

graph.BFS(0);

}
OTUPUT :

Breadth First Traversal for the graph is:

013425

RESULT :

Thus the program breadth first search was executed successfully


Ex.No. 6 Implementation of graph traversal using Depth First Search
Date :

AIM :

To write a java program for Implementation of graph traversal using Depth First Search

ALGORITHM :

1. Create a stack data structure.


2. Add the starting node to the stack.
3. Mark the starting node as visited.
4. While the stack is not empty, do the following:
a. Remove the top node from the stack.
b. For each unvisited neighbor of the current node, do the following:
i. Mark the neighbor as visited.
ii. Add the neighbor to the top of the stack.
5. Repeat steps 4 and 5 until the stack is empty.

PROGRAM :

import java.util.*;
class DFSTraversal {
private LinkedList<Integer> adj[];
private boolean visited[];
DFSTraversal(int V)
{
adj = new LinkedList[V];
visited = new boolean[V];
for (int i = 0; i < V; i++)
adj[i] = new LinkedList<Integer>();
}
void insertEdge(int src, int dest)
{adj[src].add(dest);
}
void DFS(int vertex)
{ visited[vertex] = true;
System.out.print(vertex + " ");

Iterator<Integer> it = adj[vertex].listIterator();
while (it.hasNext()) {
int n = it.next();
if (!visited[n])
DFS(n);
}
}
public static void main(String args[])
{ DFSTraversal graph = new
DFSTraversal(8);graph.insertEdge(0, 1);
graph.insertEdge(0, 2);
graph.insertEdge(0, 3);
graph.insertEdge(1, 3);
graph.insertEdge(2, 4);
graph.insertEdge(3, 5);
graph.insertEdge(3, 6);
graph.insertEdge(4, 7);
graph.insertEdge(4, 5);
graph.insertEdge(5, 2);
System.out.println("Depth First Traversal for the graph is:");
graph.DFS(0);
}
}
OUTPUT :

Depth First Traversal for the graph is:

01352476

RESULT :

Thus the program depth first search was executed successfully


Ex.No. 7 Implementation of Dijkstra’s algorithm
Date :

AIM :

To write a java program for Implementation of Dijkstra’s algorithm

ALGORITHM :

1. Create a set of unvisited nodes and a dictionary of distances.


2. Set the starting node's distance to 0 and add it to the set of unvisited nodes.
3. While there are unvisited nodes, do the following:
a. Find the node with the smallest distance in the dictionary of distances.
b. Remove this node from the set of unvisited nodes.
c. For each neighbor of the current node, do the following:
i. Calculate the distance from the starting node to the neighbor through the current node.
ii. If this distance is smaller than the current distance in the dictionary of distances, update
the distance in the dictionary.
d. Repeat steps a-c until all neighbors have been visited.
4. Return the dictionary of distances.

PROGRAM :

import java.util.*;
import java.io.*;
import java.lang.*;
public class DijkstraExample
{
static final int totalVertex = 9;
int minimumDistance(int distance[], Boolean spSet[]) 12.
{
int m = Integer.MAX_VALUE, m_index = -1;

for (int vx = 0; vx < totalVertex; vx++)


{
if (spSet[vx] == false && distance[vx] <= m)
{
m = distance[vx];
m_index = vx;
}
}
return m_index;
}
void printSolution(int distance[], int n)
{
System.out.println("The shortest Distance from source 0th node to all other
nodes are: ");
for (int j = 0; j < n; j++)
System.out.println("To " + j + " the shortest distance is: " + distance[j]);
}.
void dijkstra(int graph[][], int s)
{.
int distance[] = new int[totalVertex];
Boolean spSet[] = new Boolean[totalVertex];
for (int j = 0; j < totalVertex; j++)
{
distance[j] = Integer.MAX_VALUE;
spSet[j] = false;
}
distance[s] = 0;
for (int cnt = 0; cnt < totalVertex - 1; cnt++)
{
int ux = minimumDistance(distance, spSet);
spSet[ux] = true;
for (int vx = 0; vx < totalVertex; vx++)
if (!spSet[vx] && graph[ux][vx] != -
1 && distance[ux] != Integer.MAX_VALUE && distance[ux] + graph[ux][vx] <
distance[vx])
{
distance[vx] = distance[ux] + graph[ux][vx];
}
}
printSolution(distance, totalVertex);
}
public static void main(String argvs[])
{
int grph[][] = new int[][] { { -1, 3, -1, -1, -1, -1, -1, 7, -1 },
{ 3, -1, 7, -1, -1, -1, -1, 10, 4 },
{ -1, 7, -1, 6, -1, 2, -1, -1, 1 },
{ -1, -1, 6, -1, 8, 13, -1, -1, 3 },
{ -1, -1, -1, 8, -1, 9, -1, -1, -1 },
{ -1, -1, 2, 13, 9, -1, 4, -1, 5 },
{ -1, -1, -1, -1, -1, 4, -1, 2, 5 },
{ 7, 10, -1, -1, -1, -1, 2, -1, 6 },
{ -1, 4, 1, 3, -1, 5, 5, 6, -1 } };
Dijkstra Example obj = new DijkstraExample();
obj.dijkstra(grph, 0);
}
}
OUTPUT :

The shortest Distance from source 0th node to all other nodes are:
To 0 the shortest distance is: 0
To 1 the shortest distance is: 3
To 2 the shortest distance is: 8
To 3 the shortest distance is: 10
To 4 the shortest distance is: 18
To 5 the shortest distance is: 10
To 6 the shortest distance is: 9
To 7 the shortest distance is: 7
To 8 the shortest distance is: 7

RESULT :

Thus the program dijkstras algorithm was executed successfully


Ex.No. 8 Implementation of Prim’s algorithm
Date :

AIM :

To write a java program for implementation of Prims algorithm

ALGORITHM :

1. Create a set of unvisited nodes, a set of visited nodes, and a dictionary of minimum distances.
2. Choose a starting node and add it to the visited set.
3. For each neighbor of the starting node, add it to the unvisited set and set its minimum distance
to the weight of the edge between it and the starting node.
4. While there are unvisited nodes, do the following:
a. Find the node in the unvisited set with the smallest minimum distance in the dictionary of
minimum distances.
b. Add this node to the visited set and remove it from the unvisited set.
c. For each neighbor of the current node that is still in the unvisited set, do the following:
i. If the weight of the edge between the current node and the neighbor is smaller than the
current minimum distance for the neighbor in the dictionary of minimum distances,
update the minimum distance in the dictionary.
d. Repeat steps a-c until all nodes have been visited.
5. Return the set of visited nodes and the dictionary of minimum distances.

PROGRAM :

import java.lang.*;
import java.util.*;
import java.io.*;
class MinimumSpanningTreeExample {
private static final int countOfVertices = 9;
int findMinKeyVertex(int keys[], Boolean setOfMST[])
{
int minimum_index = -1;
int minimum_value = Integer.MAX_VALUE;
for (int vertex = 0; vertex < countOfVertices; vertex++)
if (setOfMST[vertex] == false && keys[vertex] < minimum_value)
{
minimum_value = keys[vertex];
minimum_index = vertex;
}
return minimum_index;
}
void showMinimumSpanningTree(int mstArray[], int graphArray[][])
{
System.out.println("Edge \t\t Weight");
for (int j = 1; j < countOfVertices; j++)
System.out.println(mstArray[j] + " <- > " + j + "\t \t" + graphArray[j][mstArray[j]]);
}
void designMST(int graphArray[][])
{
int mstArray[] = new int[countOfVertices];
int keys[] = new int[countOfVertices];

Boolean setOfMST[] = new Boolean[countOfVertices];


for (int j = 0; j < countOfVertices; j++)
{keys[j] = Integer.MAX_VALUE;
setOfMST[j] = false;
}
keys[0] = 0; // it select as first vertex
//mstArray[0] = -1; // set first value of mstArray to -
for (int i = 0; i < countOfVertices - 1; i++) {
int edge = findMinKeyVertex(keys, setOfMST);
setOfMST[edge] = true;
for (int vertex = 0; vertex < countOfVertices; vertex++)
if (graphArray[edge][vertex] != 0 && setOfMST[vertex] == false
&& graphArray[edge][vertex] < keys[vertex]) { mstArray[vertex]
= edge;
keys[vertex] = graphArray[edge][vertex];
}
}
showMinimumSpanningTree(mstArray, graphArray);
}
public static void main(String[] args)
{
MinimumSpanningTreeExample mst = new MinimumSpanningTreeExample();
int graphArray[][] = new int[][]{{ 0, 4, 0, 0, 0, 0, 0, 8, 0 }, { 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 }, { 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 }, { 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 }, { 0, 0, 2, 0, 0, 0, 6, 7, 0 }};
mst.designMST(graphArray); } }
OUTPUT :

Edge Weight

0 <- > 1 4

1 <- > 2 8

2 <- > 3 7

3 <- > 4 9

2 <- > 5 4

5 <- > 6 2

6 <- > 7 1

2 <- > 8 2

RESULT :

Thus the program Prims algorithm was executed successfully.


Ex.No. 9 Implementation of Floyds algorithm
Date :

AIM :

To write a java program for implementation of Floyds Algorithm

ALGORITHM :

1. Start the process


2. Create a distance matrix initialized with the weights of the edges in the graph.
3. For each intermediate node in the graph, do the following:
a. Update the distance matrix by considering all pairs of nodes (i, j)
b. checking if going through the intermediate node reduces the distance between them.
4. Return the distance matrix.
5.Stop the process

PROGRAM :

import java.util.ArrayList;
import java.util.List;
class Main
{
private static void printPath(int[][] path, int v, int u, List<Integer> route)
{
if (path[v][u] == v)
{return; }
printPath(path, v, path[v][u], route);
route.add(path[v][u]);
}
private static void printSolution(int[][] path, int n)
{
for (int v = 0; v < n; v++)
{
for (int u = 0; u < n; u++)
{
if (u != v && path[v][u] != -1)
{
List<Integer> route = new ArrayList<>();
route.add(v);
printPath(path, v, u, route);
route.add(u);
System.out.printf("The shortest path from %d —> %d is %s\n",
v, u, route);
}
}
}
}
public static void floydWarshall(int[][] adjMatrix)
{
if (adjMatrix ==null || adjMatrix.length == 0) { return;
}
int n = adjMatrix.length;
int[][] cost = new int[n][n];
int[][] path = new int[n][n];
for (int v = 0; v < n; v++)
{
for (int u = 0; u < n; u++)
{
cost[v][u] = adjMatrix[v][u];
if (v == u) {
path[v][u] = 0;
}
else if (cost[v][u] != Integer.MAX_VALUE)
{path[v][u] = v;
}
else
{ path[v][u] = -
1;
}
}
}
for (int k = 0; k < n; k++)
{
for (int v = 0; v < n; v++)
{
for (int u = 0; u < n; u++)
{
if (cost[v][k] != Integer.MAX_VALUE
&& cost[k][u] != Integer.MAX_VALUE
&& (cost[v][k] + cost[k][u] < cost[v][u]))
{
cost[v][u] = cost[v][k] + cost[k][u];
path[v][u] = path[k][u];
}
}

if (cost[v][v] < 0)
{
System.out.println("Negative-weight cycle found!!");
return;
}
}
}
printSolution(path, n); }
public static void main(String[] args)
{
int I = Integer.MAX_VALUE;
int[][] adjMatrix = new int[][]
{
{ 0, I, -2, I },
{ 4, 0, 3, I },
{ I, I, 0, 2 },
{ I, -1, I, 0 }
};
floydWarshall(adjMatrix);
}
}
OUTPUT :

The shortest path from 0 —> 1 is [0, 2, 3, 1]

The shortest path from 0 —> 2 is [0, 2]

The shortest path from 0 —> 3 is [0, 2, 3]

The shortest path from 1 —> 0 is [1, 0]

The shortest path from 1 —> 2 is [1, 0, 2]

The shortest path from 1 —> 3 is [1, 0, 2, 3]

The shortest path from 2 —> 0 is [2, 3, 1, 0]

The shortest path from 2 —> 1 is [2, 3, 1]

The shortest path from 2 —> 3 is [2, 3]

The shortest path from 3 —> 0 is [3, 1, 0]

The shortest path from 3 —> 1 is [3, 1]

The shortest path from 3 —> 2 is [3, 1, 0, 2]

RESULT ;

Thus the program Floyds algorithm was executed successfully


Ex.No. 10 Implementation of Warshall's algorithm
Date :

AIM :

To write a java program for implemenation of Warshall Algorithm

ALGORITHM :

1. Start the process


2. Create a matrix initialized with the adjacency matrix of the graph.
3. For each intermediate node in the graph, do the following:
a. Update the matrix by considering all pairs of nodes (i, j)
b. checking if there is a path from node i to node j going through the intermediate node.
4. Return the final matrix.
5.Stop the process

PROGRAM :

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Edge{
int source, dest;
public Edge(int source, int dest)
{
this.source = source;
this.dest = dest;
}
}
class Graph
{
List<List<Integer>> adjList = null;
Graph(List<Edge> edges, int n)
{
adjList = new ArrayList<>();
for (int i = 0; i < n; i++)
{ adjList.add(new
ArrayList<>());
}
for (Edge edge: edges)
{
int src = edge.source;
int dest = edge.dest; adjList.get(src).add(dest);
}
}
}
class Main
{
public static void DFS(Graph graph, byte[][] C, int root, int descendant)
{
for (int child: graph.adjList.get(descendant))
{
if (C[root][child] == 0)
{
C[root][child] = 1;
DFS(graph, C, root, child);
}
}
}
public static void main(String[] args)
{
List<Edge> edges = Arrays.asList(
new Edge(0, 2), new Edge(1, 0), new Edge(3, 1)
);
Graph graph = new Graph(edges, n);
byte C[][] = new byte[n][n];
for (int v = 0; v < n; v++)
{
C[v][v] = 1;
DFS(graph, C, v, v);
System.out.println(Arrays.toString(C[v]));
}
}
}
OUTPUT :

[1, 0, 1, 0]

[1, 1, 1, 0]

[0, 0, 1, 0]

[1, 1, 1, 1]

RESULT :

Thus the program Warshall algorithm was executed successfully


Ex.No. 11 Develop an application using the divide and conquer technique
Date :

AIM :

To write a java program for implemenation of Divide And Conquer

ALGORITHM :

1. Define a base case for the problem that can be solved directly without recursion.
2. Divide the problem into smaller subproblems that can be solved recursively.
3. Conquer each subproblem by solving it recursively.
4. Combine the solutions of the subproblems to solve the original problem.
5.Stop the process

PROGRAM :

public class MaxMinDivideAndConquer


{public static void main(String[] args)
{ int[] arr = {7, 2, 9, 3, 5, 1, 8, 6, 4};
int n = arr.length;
Pair result = findMaxMin(arr, 0, n - 1);
System.out.println("Maximum number is: " + result.max);
System.out.println("Minimum number is: " + result.min);
}

public static Pair findMaxMin(int[] arr, int left, int right)


{if (left == right) {
return new Pair(arr[left], arr[right]);
} else if (right - left == 1)
{if (arr[left] < arr[right])
{
return new Pair(arr[right], arr[left]);
} else {
return new Pair(arr[left], arr[right]);
}
} else {
int mid = (left + right) / 2;
Pair leftResult = findMaxMin(arr, left, mid);
Pair rightResult = findMaxMin(arr, mid + 1, right);
int max = Math.max(leftResult.max, rightResult.max);
int min = Math.min(leftResult.min, rightResult.min);
return new Pair(max, min);
}
}
}

class Pair
{int max;
int min;

public Pair(int max, int min)


{this.max = max;
this.min = min;
}
}
OUTPUT :

Maximum number is: 9

Minimum number is: 1

RESULT :

Thus the program Divide Conquer was executed successfully


Ex.No. 12A Implement Quick sort
Date :

AIM :

To write a java program for implementation of Quick Sort

ALGORITHM :

1. Choose the highest index value has pivot


2. Take two variables to point left and right of the list excluding pivot
3. left points to the low index
4.right points to the high
5.while value at left is less than pivot move right
6.while value at right is greater than pivot move left
7. if both step 5 and step 6 does not match swap left and right
8. if left ≥ right, the point where they met is new pivot

PROGRAM :

import java.util.Arrays;
public class QuickSort {
public static void main(String[] args)
{int[] arr = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
long startTime = System.nanoTime();
quickSort(arr, 0, arr.length - 1);
long endTime = System.nanoTime();
long duration = (endTime - startTime) / 1000000; // Convert to milliseconds
System.out.println("Sorted array: " + Arrays.toString(arr));
System.out.println("Time taken: " + duration + " milliseconds");
}
public static void quickSort(int[] arr, int low, int high)
{if (low < high) {
int pivot = partition(arr, low, high);
quickSort(arr, low, pivot - 1);
quickSort(arr, pivot + 1, high);
}
}
private 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++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
return i + 1;
}
private static void swap(int[] arr, int i, int j)
{int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
OUTPUT :

Sorted array: [1, 1, 2, 3, 3, 4, 5, 5, 6, 9]

Time taken: 0 milliseconds

RESULT :

Thus the program Quick Sort was executed successfully


Ex.No. 12B Implement Merge sort
DATE :

AIM :

To write a java program implementation for Merge Sort

ALGORITHM :

1.Divide the array into two parts


2.Divide the array into two part again
3.Break the each element into single parts
4.Sort the elements into smallest to largest
5.Merged the divided sorted array together
6.The array has been sorted

PROGRAM :

import java.util.Arrays;
public class MergeSortExample
{ public static void main(String[] args)
{
int[] arr = { 5, 1, 9, 3, 7, 4, 6, 2, 8 };
System.out.println("Unsorted Array: " + Arrays.toString(arr));
long startTime = System.nanoTime();
mergeSort(arr, 0, arr.length - 1);
long endTime = System.nanoTime();
System.out.println("Sorted Array: " + Arrays.toString(arr));
long timeRequired = endTime - startTime;
System.out.println("Time Required: " + timeRequired + " nanoseconds");
}

public static void mergeSort(int[] arr, int start, int end)


{if (start < end) {
int mid = (start + end) / 2;
mergeSort(arr, start, mid);
mergeSort(arr, mid + 1, end);
merge(arr, start, mid, end);
}
}

public static void merge(int[] arr, int start, int mid, int end)
{int n1 = mid - start + 1;
int n2 = end - mid; int[]
left = new int[n1];
int[] right = new int[n2];
for (int i = 0; i < n1; ++i)
{left[i] = arr[start + i];
}
for (int j = 0; j < n2; ++j)
{right[j] = arr[mid + 1 +
j];
}
int i = 0, j = 0;
int k = start;
while (i < n1 && j < n2)
{if (left[i] <= right[j])
{arr[k] = left[i];
i++;
} else {
arr[k] = right[j];
j++;
}
k++;
}
while (i < n1)
{arr[k] = left[i];
i++;
k++;
}
while (j < n2)
{ arr[k] =
right[j];j++;
k++;
}
}
}
OUTPUT :

Unsorted Array: [5, 1, 9, 3, 7, 4, 6, 2, 8]

Sorted Array: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Time Required: 14457 nanoseconds

RESULT :

Thus the program Merge Sort was executed successfully


Ex.No. 13 Implement N Queens problem using Backtracking
Date :

AIM :

To write a java program for Implement N Queens problem using Backtracking

ALGORITHM :

1. Start with an empty chessboard of size n x n.


2. Place the first queen in the top-left corner of the board (i.e., row 1, column 1).
3. Move to the next row and try to place a queen in each column until a valid position is found or
all columns have been tried.
4. If a valid position is found, move to the next row and repeat step 3.
5. If all columns have been tried in the current row without finding a valid position, backtrack to
the previous row and move the queen to the next column in that row. Repeat step 3.
6. If all rows have been tried without finding a solution, backtrack to the previous row and move
the queen to the next column in that row. Repeat step 3.
7. If a solution is found, print the positions of the queens on the board and exit the program.

PROGRAM :

public class NQueens


{int N;
int[] queenPositions;

public NQueens(int N)
{this.N = N;
this.queenPositions = new int[N];
}

public void solve()


{if (placeQueen(0))
{
printSolution();
} else {
System.out.println("No solution exists for " + N + " Queens.");
}
}

private boolean placeQueen(int row)


{if (row == N)
{return true;
}
for (int col = 0; col < N; col++)
{if (isSafe(row, col))
{ queenPositions[row] =
col;if (placeQueen(row +
1)) {
return true;
}
}
}
return false;
}

private boolean isSafe(int row, int col)


{for (int i = 0; i < row; i++) {
if (queenPositions[i] == col ||
queenPositions[i] - i == col - row ||
queenPositions[i] + i == col + row)
{return false;
}
}
return true;
}

private void printSolution() {


for (int row = 0; row < N; row++)
{for (int col = 0; col < N; col++)
{
if (queenPositions[row] == col)
{System.out.print("Q ");
} else {
System.out.print("- ");
}
}
System.out.println();
}
}

public static void main(String[] args)


{NQueens nq = new NQueens(4);
nq.solve();
}}
OUTPUT :

- Q - -

- - - Q

Q - - -

- - Q -

RESULT :

Thus the program N queens problem was executed successfully


Ex.No. 14 Develop an application using approximation algorithm
Date :

AIM :

TO write a java program for to Develop an application using approximation algorithm

ALGORITHM :

1. Travelling salesman problem takes a graph G {V, E} as an input and declare another graph as
the output (say G’) which will record the path the salesman is going to take from one node to
another.
2. The algorithm begins by sorting all the edges in the input graph G from the least distance to the
largest distance.
3. The first edge selected is the edge with least distance, and one of the two vertices (say A and B)
being the origin node (say A).
4. Then among the adjacent edges of the node other than the origin node (B), find the least cost
edge and add it onto the output graph.
5. Continue the process with further nodes making sure there are no cycles in the output graph
and the path reaches back to the origin node A.
6. However, if the origin is mentioned in the given problem, then the solution must always start
from that node only. Let us look at some example problems to understand this better

PROGRAM :

import java.util.*;
public class TSP {
int N;
int[][] distances;
int[] tour;
int tourLength;
public TSP(int N, int[][] distances)
{this.N = N;
this.distances = distances;
this.tour = new int[N];
}
public void solve() {
int[] cities = new int[N];
for (int i = 0; i < N; i++) {
cities[i] = i;
}
permute(cities, 0);
System.out.println("Optimal tour: " + Arrays.toString(tour));
System.out.println("Optimal tour length: " + tourLength);
int[] approxTour = new int[N];
boolean[] visited = new boolean[N];
Random rand = new Random();
int start = rand.nextInt(N);
approxTour[0] = start;
visited[start] = true;
for (int i = 1; i < N; i++) {
int prev = approxTour[i-1];
int next = -1;
int minDist = Integer.MAX_VALUE;
for (int j = 0; j < N; j++) {
if (!visited[j] && distances[prev][j] < minDist)
{minDist = distances[prev][j];
next = j;
}
}
approxTour[i] = next;
visited[next] = true;
}
int approxLength = tourLength(approxTour);
System.out.println("Approximate tour: " + Arrays.toString(approxTour));
System.out.println("Approximate tour length: " + approxLength);
double error = ((double) approxLength - tourLength) / tourLength * 100;
System.out.println("Error in approximation: " + error + "%");
}
private void permute(int[] cities, int start)
{if (start == N) {
int length = tourLength(cities);
if (tourLength == 0 || length < tourLength)
{tourLength = length;
System.arraycopy(cities, 0, tour, 0, N);
}
} else {
for (int i = start; i < N; i++)
{swap(cities, start, i);
permute(cities, start + 1);
swap(cities, start, i);
}
}
}
private int tourLength(int[] cities)
{int length = 0;
for (int i = 0; i < N; i++) {
length += distances[cities[i]][cities[(i+1) % N]];
}
return length;
}

private void swap(int[] cities, int i, int j)


{int temp = cities[i];
cities[i] = cities[j];
cities[j] = temp;
}
public static void main(String[] args)
{int N = 4;
int[][] distances = {{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}};
TSP tsp = new TSP(N, distances);
tsp.solve();
}
}
OUTPUT :

Optimal tour: [0, 1, 3, 2]

Optimal tour length: 80

Approximate tour: [3, 0, 1, 2]

Approximate tour length: 95

Error in approximation: 18.75%

RESULT :

Thus the program Travelling Salesperson Problem was executed successfully


Ex.No. 15 Implementation of randomized algorithms
Date :

AIM :

To write a java program for Implementation of randomized algorithms

ALGORITHM :

1. Start by defining the input array and the value of k.


2. Sort the array in ascending order using any sorting algorithm (such as QuickSort or
MergeSort).
3. Return the element at the k-1 index of the sorted array as the kth smallest element.
4.Stop the process

PROGRAM :

import java.util.*;
public class RandomizedSelect {
public static int randomizedSelect(int[] arr, int k)
{int left = 0;
int right = arr.length - 1;
Random rand = new Random();
while (left <= right) {
int pivotIndex = rand.nextInt(right - left + 1) + left;
int newPivotIndex = partition(arr, left, right, pivotIndex);
int rank = newPivotIndex - left + 1;
if (rank == k) {
return arr[newPivotIndex];
} else if (k < rank) {
right = newPivotIndex - 1;
} else {
k -= rank;
left = newPivotIndex + 1;
}
}
return -1;
}
private static int partition(int[] arr, int left, int right, int pivotIndex)
{int pivotValue = arr[pivotIndex];
swap(arr, pivotIndex, right);
int storeIndex = left;
for (int i = left; i < right; i++)
{if (arr[i] < pivotValue)
{ swap(arr, i,
storeIndex);
storeIndex++;
}
}
swap(arr, storeIndex, right);
return storeIndex;
}

private static void swap(int[] arr, int i, int j)


{int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

public static void main(String[] args)


{int[] arr = {4, 7, 1, 3, 9, 2, 5, 8, 6};
int k = 3;
int kthSmallest = randomizedSelect(arr, k);
System.out.println("The " + k + "th smallest element is: " + kthSmallest);
}
}
OUTPUT :

The 3th smallest element is: 3

RESULT :

Thus the program Travelling Salesperson Problem was executed successfully

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