Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Algorithms Lab Updated

Uploaded by

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

Algorithms Lab Updated

Uploaded by

kishorelalith804
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

T.J.

S ENGINEERING COLLEGE

(Approved by AICTE &Affiliated to Anna University, Chennai)

Peruvoyal, (Near Kavarapettai),

Gummidipoondi Taluk,

Thiruvallur District-601206

NAME : ………………………………………………

REG NO : ……………………………………….

DEPARTMENT : ..…………………………………………….

SUBJECT CODE : ………………………………………………

YEAR/SEM : ………………………………………………

1
T.J.S ENGINEERING COLLEGE
(Approved by AICTE &Affiliated to Anna University, Chennai)
Peruvoyal, (Near Kavaraipettai), Gummidipoondi Taluk,
Thiruvallur District-601206.

NAME : …………………………………………

DEPARTMENT : …………………………………………

SUBJECT CODE /TITLE : …………………………………

YEAR/SEM : ………………………………………

DATE OF EXAMINATION : ……………………………………….

REGISTER NUMBER :

Certified that this is the Bonafide record of practical work done by the aforesaid student in the
during the year
.

Laboratory in charge Head of the Department

Internal Examiner External Examiner

2
INDEX

S.NO NAME OF THE EXPERIMENTS DATE SIGN

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

AIM:
To write a Java program to implement Linear search.

ALGORITHM:
Step 1: Traverse the array

Step 2: Match the key element with array element

Step 3: If key element is found, return the index position of the array element

Step 4: If key element is not found, return -1

PROGRAM:
public class LinearSearchExample{
public static int linearSearch(int[] arr, int key){
for(int i=0;i<arr.length;i++){
if(arr[i] == key){
return i;
}
}
return -1;
}
public static void main(String a[]){
int[] a1= {10,20,30,50,70,90};
int key = 50;
System.out.println(key+" is found at index: "+linearSearch(a1, key));
}
}

OUTPUT:

50 is found at index: 3

RESULT :
Thus the program successfully compiled and executed.

5
EX.NO: 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
DATE: the time taken versus n.

AIM
To write a Java program to implement Binary Search.

ALGORITHM:

1. Calculate the mid element of the collection.


2. Compare the key items with the mid element.
3. If key = middle element, then we return the mid index position for the key found.
4. Else If key > mid element, then the key lies in the right half of the collection. Thus repeat steps 1 to 3
on the lower (right) half of the collection.
5. Else key < mid element, then the key is in the upper half of the collection. Hence you need to repeat
the binary search in the upper half.

6
PROGRAM:

class BinarySearchExample{
public static void binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
System.out.println("Element is found at index: " + mid);
break;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
System.out.println("Element is not found!");
}
}
public static void main(String args[]){
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
binarySearch(arr,0,last,key);
}
}

OUTPUT:

Element is found at index: 2

7
RESULT :
Thus the program successfully compiled and executed.

8
EX.NO: 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.
DATE:

Aim
To write a JAVA program to create a String matching algorithm,

ALGORITHM

1. Take text and pattern as input.


2. Run an outer for loop from 0 to length of text-length of the pattern.
3. Run an inner loop from 0 to the length of the pattern.
4. Through this,, for each character at each index in the text starting from that index till
index+length of pattern, the pattern is searched in the text.
5. If the pattern is found, print the index of the outer loop at which that pattern is found in the
text.
6. Else if the pattern is not found, then print it is not found.

PROGRAM:

import java.io.*;

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

String text = "geeksforgeeks is a coding website for geeks";


String pattern = "geeks";

// calling the method that is designed for


// printing the instances of pattern
// found in the text string
stringMatch(text, pattern);

9
}
public static void stringMatch(String text, String pattern)
{

int len_t = text.length();


int len_p = pattern.length();

int k = 0, i = 0, j = 0;

// loop to find out the position Of searched pattern


for (i = 0; i <= (len_t - len_p); i++) {

for (j = 0; j < len_p; j++)


{
if (text.charAt(i + j) != pattern.charAt(j))
break;
}

if (j == len_p)
{
k++;
System.out.println("Pattern Found at Position: " + i);
}
}

if (k == 0)
System.out.println("No Match Found!");
else
System.out.println("Total Instances Found = " + k);
10
}
}

OUTPUT:
Pattern Found at Position: 0
Pattern Found at Position: 8
Pattern Found at Position: 38
Total Instances Found = 3

RESULT :
Thus the program successfully compiled and executed.

11
EX.NO: 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
DATE: plot a graph of the time taken versus n.

Aim
To write a Java program to create a Insertion sort

ALGORITHM

Step 1 - If the element is the first element, assume that it is already sorted. Return 1.

Step2 - Pick the next element, and store it separately in a key.

Step3 - Now, compare the key with all elements in the sorted array.

Step 4 - If the element in the sorted array is smaller than the current element, then move to the next element.
Else, shift greater elements in the array towards the right.

Step 5 - Insert the value.

Step 6 - Repeat until the array is sorted.

PROGRAM:

public class Insert


{
void insert(int a[]) /* function to sort an aay with insertion sort */
{
int i, j, temp;
int n = a.length;
for (i = 1; i < n; i++) {
temp = a[i];
j = i - 1;

while(j>=0 && temp <= a[j]) /* Move the elements greater than temp to one position ahead from their curr
ent position*/
{
a[j+1] = a[j];
j = j-1;
}

12
a[j+1] = temp;
}
}
void printArr(int a[]) /* function to print the array */
{
int i;
int n = a.length;
for (i = 0; i < n; i++)
System.out.print(a[i] + " ");
}

public static void main(String[] args) {


int a[] = { 92, 50, 5, 20, 11, 22 };
Insert i1 = new Insert();
System.out.println("\nBefore sorting array elements are - ");
i1.printArr(a);
i1.insert(a);
System.out.println("\n\nAfter sorting array elements are - ");
i1.printArr(a);
System.out.println();
}
}

OUTPUT:

RESULT :
Thus the program to implement Insertion sort was implemented and successfully
executed

13
Aim
To write a Java program to create a Heap sort.

ALGORITHM

In heap sort, basically, there are two phases involved in the sorting of elements. By using the heap sort
algorithm, they are as follows -

o The first step includes the creation of a heap by adjusting the elements of the array.
o After the creation of heap, now remove the root element of the heap repeatedly by shifting it to the
end of the array, and then store the heap structure with the remaining elements.

PROGRAM:

class HeapSort
{
/* function to heapify a subtree. Here 'i' is the
index of root node in array a[], and 'n' is the size of heap. */
static void heapify(int a[], int n, int i)
{
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // left child
int right = 2 * i + 2; // right child
// If left child is larger than root
if (left < n && a[left] > a[largest])
largest = left;
// If right child is larger than root
if (right < n && a[right] > a[largest])
largest = right;
// If root is not largest
if (largest != i) {
// swap a[i] with a[largest]
int temp = a[i];
a[i] = a[largest];
a[largest] = temp;

heapify(a, n, largest);
}
}

14
/*Function to implement the heap sort*/
static void heapSort(int a[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(a, n, i);

// One by one extract an element from heap


for (int i = n - 1; i >= 0; i--) {
/* Move current root element to end*/
// swap a[0] with a[i]
int temp = a[0];
a[0] = a[i];
a[i] = temp;

heapify(a, i, 0);
}
}
/* function to print the array elements */
static void printArr(int a[], int n)
{
for (int i = 0; i < n; ++i)
System.out.print(a[i] + " ");
}
public static void main(String args[])
{
int a[] = {45, 7, 20, 40, 25, 23, -2};
int n = a.length;
System.out.print("Before sorting array elements are - \n");
printArr(a, n);
heapSort(a, n);
System.out.print("\nAfter sorting array elements are - \n");
printArr(a, n);
}
}

15
OUTPUT:

RESULT :
Thus the program to implement heap sort was implemented and successfully
executed.

16
EX.NO: Develop a program to implement graph traversal using Breadth First
Search

DATE:

Aim
To write a Java program to create a Breadth First search.

ALGORITHM

1. Take the data for the graph's adjacency matrix or adjacency list.
2. Create a queue and fill it with items.
3. Activate the root node (meaning that get the root node at the beginning of the queue).
4. Dequeue the queue's head (or initial element), then enqueue all of the queue's nearby nodes from left
to right. Simply dequeue the head and resume the operation if a node has no nearby nodes that need to
be investigated. (Note: If a neighbor emerges that has previously been investigated or is in the queue,
don't enqueue it; instead, skip it.)
5. Continue in this manner until the queue is empty.

PROGRAM:

OUTPUT:
import java.io.*;
import java.util.*;
public class BFSTraversal
{
private int node; /* total number number of nodes in the graph */
private LinkedList<Integer> adj[]; /* adjacency list */
private Queue<Integer> que; /* maintaining a queue */
BFSTraversal(int v)
{
node = v;
adj = new LinkedList[node];
for (int i=0; i<v; i++)
{
adj[i] = new LinkedList<>();
}
17
que = new LinkedList<Integer>();
}

void insertEdge(int v,int w)


{
adj[v].add(w); /* adding an edge to the adjacency list (edges are bidirectional in this example) */
}
void BFS(int n)
{
boolean nodes[] = new boolean[node]; /* initialize boolean array for holding the data */
int a = 0;
nodes[n]=true;
que.add(n); /* root node is added to the top of the queue */
while (que.size() != 0)
{
n = que.poll(); /* remove the top element of the queue */
System.out.print(n+" "); /* print the top element of the queue */
for (int i = 0; i < adj[n].size(); i++) /* iterate through the linked list and push all neighbors into queue */

{
a = adj[n].get(i);
if (!nodes[a]) /* only insert nodes into queue if they have not been explored already */
{
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);
18
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);
}
}

Output:

Breadth First Traversal for the graph is:


013425

RESULT :
Thus the program to implement Breadth First Search was implemented and
successfully executed.

19
EX.NO: Develop a program to implement graph traversal using Depth First
Search

DATE:

Aim
To write a Java program to create a Depth First search

ALGORITHM

Step 1: SET STATUS = 1 (ready state) for each node in G

Step 2: Push the starting node A on the stack and set its STATUS = 2 (waiting state)

Step 3: Repeat Steps 4 and 5 until STACK is empty

Step 4: Pop the top node N. Process it and set its STATUS = 3 (processed state)

Step 5: Push on the stack all the neighbors of N that are in the ready state (whose STATUS = 1) and set their
STATUS = 2 (waiting state)

[END OF LOOP]

Step 6: EXIT

PROGRAM:

import java.util.*;

class DFSTraversal {
private LinkedList<Integer> adj[]; /*adjacency list representation*/
private boolean visited[];

/* Creation of the graph */


DFSTraversal(int V) /*'V' is the number of vertices in the graph*/
{
adj = new LinkedList[V];
visited = new boolean[V];

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


adj[i] = new LinkedList<Integer>();
}
20
/* Adding an edge to the graph */
void insertEdge(int src, int dest) {
adj[src].add(dest);
}

void DFS(int vertex) {


visited[vertex] = true; /*Mark the current node as visited*/
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);
}
}

21
OUTPUT:

RESULT :
Thus the program to implement Depth First Search was implemented and
successfully executed.

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

Aim
To write a Java program to create a Dijkstra’s algorithm.

ALGORITHM

Step1: All nodes should be marked as unvisited.

Step2: All the nodes must be initialized with the "infinite" (a big number) distance. The starting node must be
initialized with zero.

Step3: Mark starting node as the current node.

Step4: From the current node, analyze all of its neighbors that are not visited yet, and compute their distances
by adding the weight of the edge, which establishes the connection between the current node and neighbor
node to the current distance of the current node.

Step5: Now, compare the recently computed distance with the distance allotted to the neighboring node, and
treat it as the current distance of the neighboring node,

Step6: After that, the surrounding neighbors of the current node, which has not been visited, are considered,
and the current nodes are marked as visited.

Step7: When the ending node is marked as visited, then the algorithm has done its job; otherwise,

Step8: Pick the unvisited node which has been allotted the minimum distance and treat it as the new current
node. After that, start again from step4.

PROGRAM:

import java.util.*;
import java.io.*;
import java.lang.*;

public class DijkstraExample


{
// A utility method to compute the vertex with the distance value, which is minimum
// from the group of vertices that has not been included yet
static final int totalVertex = 9;
23
int minimumDistance(int distance[], Boolean spSet[])
{
// Initialize min value
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;

// A utility method to display the built distance array


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

// method that does the implementation of Dijkstra's shortest path algorithm


// for a graph that is being represented using the adjacency matrix representation
void dijkstra(int graph[][], int s)
{
int distance[] = new int[totalVertex]; // The output array distance[i] holds the shortest distance from source s to j

// spSet[j] will be true if vertex j is included in the shortest


// path tree or the shortest distance from the source s to j is finalized
Boolean spSet[] = new Boolean[totalVertex];

// Initializing all of the distances as INFINITE


// and spSet[] as false
for (int j = 0; j < totalVertex; j++)
24
{
distance[j] = Integer.MAX_VALUE;
spSet[j] = false;
}

// Distance from the source vertex to itself is always 0


distance[s] = 0;

// compute the shortest path for all the given vertices


for (int cnt = 0; cnt < totalVertex - 1; cnt++)
{
// choose the minimum distance vertex from the set of vertices
// not yet processed. ux is always equal to source s in the first
// iteration.
int ux = minimumDistance(distance, spSet);

// the choosed vertex is marked as true


// it means it is processed
spSet[ux] = true;

// Updating the distance value of the neighboring vertices


// of the choosed vertex.
for (int vx = 0; vx < totalVertex; vx++)

// Update distance[vx] if and only if it is not in the spSet, there is an


// edge from ux to vx, and the total weight of path from source s to
// vx through ux is lesser than the current value of distance[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];
}
}

// display the build distance array


printSolution(distance, totalVertex);
}

// main method
25
public static void main(String argvs[])
{
// A 9 * 9 matrix is created.
// arr[x][y] = - 1 means, there is no any edge that connects the nodes x and y directly
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 } };

// creating an object of the class DijkstraExample


DijkstraExample 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 to implement Dijkstra’s algorithm was implemented and
successfully executed.

26
EX.NO: Find the minimum cost spanning tree of a given undirected graph
using Prim’s algorithm

DATE:

Aim
To write a Java program to create a Prim’s algorithm

ALGORITHM
1. Create any collection that contains only unique elements keeps track of vertices already included in
MST.
2. For all the vertices of the input graph, assign a key-value pair and set the value to infinite. In order to
pick the first vertex, we set its key value as 0.
3. Select a vertex u that is not present in the setOfMST and having a minimum key value.
4. Add vertex u to the setOfMST.
5. Change the key value of all adjacent vertices of u.
6. Repeat steps 3, 4, and 5 until the setOfMST doesn't contain all vertices.

PROGRAM:

import java.lang.*;
import java.util.*;
import java.io.*;

//creating MinimumSpanningTreeExample class to implement Prim's algorithm in Java


class MinimumSpanningTreeExample {
// Define the count of vertices available in the graph
private static final int countOfVertices = 9;

// create findMinKeyVertex() method for finding the vertex v that has minimum key-
value and that is not added MST yet
int findMinKeyVertex(int keys[], Boolean setOfMST[])
{
// Initialize min value and its index
int minimum_index = -1;
int minimum_value = Integer.MAX_VALUE;

27
//iterate over all vertices to find minimum key-value vertex
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;
}

// create showMinimumSpanningTree for printing the constructed MST stored in mstArray[]


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

// create designMST() method for constructing and printing the MST. The graphArray[][] is an adjacency matr
ix that defines the graph for MST.
void designMST(int graphArray[][])
{
// create array of size total number of vertices, i.e., countOfVertices for storing the MST
int mstArray[] = new int[countOfVertices];

// create keys[] array for selecting an edge having minimum weight in cut
int keys[] = new int[countOfVertices];

// create setOfMST array of type boolean for representing the set of vertices included in MST
Boolean setOfMST[] = new Boolean[countOfVertices];

// set the value of the keys to infinite


for (int j = 0; j < countOfVertices; j++) {
keys[j] = Integer.MAX_VALUE;
setOfMST[j] = false;
}

// set value 0 to the 1st vertex because first vertes always include in MST.
28
keys[0] = 0; // it select as first vertex
mstArray[0] = -1; // set first value of mstArray to -1 to make it root of MST

// The vertices in the MST will be equal to the countOfVertices


for (int i = 0; i < countOfVertices - 1; i++) {
// select the vertex having minimum key and that is not added in the MST yet from the set of vertices
int edge = findMinKeyVertex(keys, setOfMST);

// Add the selected minimum key vertex to the setOfMST


setOfMST[edge] = true;

// change the key value and the parent index of all the adjacent vertices of the selected vertex. The vertice
s that are not yet included in Minimum Spanning Tree are only considered.
for (int vertex = 0; vertex < countOfVertices; vertex++)

// The value of the graphArray[edge][vertex] is non zero only for adjacent vertices of m setOfMST[vert
ex] is false for vertices not yet included in Minimum Spanning Tree
// when the value of the graphArray[edge][vertex] is smaller than key[vertex], we update the key
if (graphArray[edge][vertex] != 0 && setOfMST[vertex] == false && graphArray[edge][vertex] < key
s[vertex]) {
mstArray[vertex] = edge;
keys[vertex] = graphArray[edge][vertex];
}
}

// print the constructed Minimum Spanning Tree


showMinimumSpanningTree(mstArray, graphArray);
}
//main() method start
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 },
29
{ 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 }};

// Print the Minimum Spanning Tree solution


mst.designMST(graphArray);
}
}

OUTPUT:

RESULT :
Thus the program to implement Prim’s algorithm was implemented and successfully
executed.

30
EX.NO: Implement Floyd’s algorithm for the All-Pairs- Shortest-Paths
problem.

DATE:

Aim
To write a Java program to implement Floyd’s algorithm for the All-Pairs- Shortest-Paths problem.

ALGORITHM
1. Initialize the solution matrix same as the input graph matrix as a first step.
2. Then update the solution matrix by considering all vertices as an intermediate vertex.
3. The idea is to one by one pick all vertices and updates all shortest paths which include the
picked vertex as an intermediate vertex in the shortest path.
4. When we pick vertex number k as an intermediate vertex, we already have considered
vertices {0, 1, 2, .. k-1} as intermediate vertices.
5. For every pair (i, j) of the source and destination vertices respectively, there are two
possible cases.
6. k is not an intermediate vertex in shortest path from i to j. We keep the value of dist[i][j]
as it is.
7. k is an intermediate vertex in shortest path from i to j. We update the value of dist[i][j] as
dist[i][k] + dist[k][j] if dist[i][j] > dist[i][k] + dist[k][j]

PROGRAM:

// Java program for Floyd Warshall All Pairs Shortest


// Path algorithm.
import java.io.*;
import java.lang.*;
import java.util.*;

class AllPairShortestPath {
final static int INF = 99999, V = 4;

void floydWarshall(int dist[][])


{

int i, j, k;

/* Add all vertices one by one


to the set of intermediate
vertices.
---> Before start of an iteration,
we have shortest
distances between all pairs
of vertices such that
the shortest distances consider
only the vertices in
31
set {0, 1, 2, .. k-1} as
intermediate vertices.
----> After the end of an iteration,
vertex no. k is added
to the set of intermediate
vertices and the set
becomes {0, 1, 2, .. k} */
for (k = 0; k < V; k++) {
// Pick all vertices as source one by one
for (i = 0; i < V; i++) {
// Pick all vertices as destination for the
// above picked source
for (j = 0; j < V; j++) {
// If vertex k is on the shortest path
// from i to j, then update the value of
// dist[i][j]
if (dist[i][k] + dist[k][j]
< dist[i][j])
dist[i][j]
= dist[i][k] + dist[k][j];
}
}
}

// Print the shortest distance matrix


printSolution(dist);
}

void printSolution(int dist[][])


{
System.out.println(
"The following matrix shows the shortest "
+ "distances between every pair of vertices");
for (int i = 0; i < V; ++i) {
for (int j = 0; j < V; ++j) {
if (dist[i][j] == INF)
System.out.print("INF ");
else
System.out.print(dist[i][j] + " ");
}
System.out.println();
}
}

// Driver's code
public static void main(String[] args)
{

int graph[][] = { { 0, 5, INF, 10 },{ INF, 0, 3, INF },{ INF, INF, 0, 1 },{ INF, INF, INF, 0 } };

AllPairShortestPath a = new AllPairShortestPath();

32
// Function call
a.floydWarshall(graph);
}
}

OUTPUT:

The following matrix shows the shortest distances between every pair of vertices
0 5 8 9
INF 0 3 4
INF INF 0 1
INF INF INF 0

RESULT :
Thus the program to implement Floyd’s algorithm was implemented and successfully
executed.

33
EX.NO: Compute the transitive closure of a given directed graph using Warshall's
algorithm.

DATE:

Aim
To write a Java program to create a Warshall’s algorithm.

ALGORITHM

1. Instead of an integer resultant matrix (dist[V][V] in floyd warshall), we can create a boolean reach-ability
matrix reach[V][V] (we save space). The value reach[i][j] will be 1 if j is reachable from i, otherw ise 0.
2. Instead of using arithmetic operations, we can use logical operations. For arithmetic operation ‘+’, logical
and ‘&&’ is used, and for a ‘-‘, logical or ‘||’ is used. (We save time by a constant factor. Time complexity
is the same though)

PROGRAM:

// Program for transitive closure


// using Floyd Warshall Algorithm
import java.util.*;
import java.lang.*;
import java.io.*;

class GraphClosure
{
final static int V = 4; //Number of vertices in a graph

// Prints transitive closure of graph[][] using Floyd


// Warshall algorithm
void transitiveClosure(int graph[][])
{
/* reach[][] will be the output matrix that will finally
have the shortest distances between every pair of
vertices */
int reach[][] = new int[V][V];
int i, j, k;

/* Initialize the solution matrix same as input graph


matrix. Or we can say the initial values of shortest
distances are based on shortest paths considering
no intermediate vertex. */
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
reach[i][j] = graph[i][j];

/* Add all vertices one by one to the set of intermediate


34
vertices.
---> Before start of a iteration, we have reachability
values for all pairs of vertices such that the
reachability values consider only the vertices in
set {0, 1, 2, .. k-1} as intermediate vertices.
----> After the end of a iteration, vertex no. k is
added to the set of intermediate vertices and the
set becomes {0, 1, 2, .. k} */
for (k = 0; k < V; k++)
{
// Pick all vertices as source one by one
for (i = 0; i < V; i++)
{
// Pick all vertices as destination for the
// above picked source
for (j = 0; j < V; j++)
{
// If vertex k is on a path from i to j,
// then make sure that the value of reach[i][j] is 1
reach[i][j] = (reach[i][j]!=0) ||
((reach[i][k]!=0) && (reach[k][j]!=0))?1:0;
}
}
}

// Print the shortest distance matrix


printSolution(reach);
}

/* A utility function to print solution */


void printSolution(int reach[][])
{
System.out.println("Following matrix is transitive closure"+
" of the given graph");
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++) {
if ( i == j)
System.out.print("1 ");
else
System.out.print(reach[i][j]+" ");
}
System.out.println();
}
}

// Driver Code
public static void main (String[] args)
{
/* Let us create the following weighted graph
10

35
(0)------->(3)
| /|\
5| |
| |1
\|/ |
(1)------->(2)
3 */

/* Let us create the following weighted graph


*/
int graph[][] = new int[][]{ {1, 1, 0, 1},
{0, 1, 1, 0},
{0, 0, 1, 1},
{0, 0, 0, 1}
};

// Print the solution


GraphClosure g = new GraphClosure();
g.transitiveClosure(graph);
}
}

OUTPUT:

Following matrix is transitiveclosure of the given graph


1111
0111
0011
0001

RESULT :
Thus the program to implement Warshalls’s algorithm was implemented and
successfullyexecuted.

36
EX.NO:
Develop a program to find out the maximum and minimum numbers
in a given list of n numbers using the divide and conquer technique.
DATE:

Aim
To write a Java program to create a singly linked list.

ALGORITHM

1. Initialize an array.
2. Sort the array in ascending order.
3. The first element of the array will be the minimum element.
4. The last element of the array will be the maximum element.
5. Print the minimum and maximum element.

PROGRAM:

static class pair {


int min;
int max;
};

import java.util.Arrays;

class Pair {
public int min;
public int max;
}

class Main {
static Pair getMinMax(int arr[], int n) {
Pair minmax = new Pair();
Arrays.sort(arr);
minmax.min = arr[0];
minmax.max = arr[n - 1];
return minmax;
}

public static void main(String[] args) {


int arr[] = { 1000, 11, 445, 1, 330, 3000 };
int arr_size = arr.length;
Pair minmax = getMinMax(arr, arr_size);
System.out.println("Minimum element is " + minmax.min);
System.out.println("Maximum element is " + minmax.max);
}
37
}

OUTPUT:

Minimum element is 1
Maximum element is 3000

RESULT :
Thus the program was implemented and successfullyexecuted.

38
EX.NO: Implement Merge 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.
DATE:

Aim
To write a Java program to create a merge sort.
ALGORITHM
step 1: start
step 2: declare array and left, right, mid variable
step 3: perform merge function.
if left > right
return
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
step 4: Stop

PROGRAM:

/* Java program for Merge Sort */


class MergeSort {
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;

/* Create temp arrays */


int L[] = new int[n1];
int R[] = new int[n2];

/*Copy data to temp arrays*/


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 temp arrays */

// Initial indexes of first and second subarrays


int i = 0, j = 0;
39
// Initial index of merged subarray array
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++;
}
}

// Main function that sorts arr[l..r] using


// merge()
void sort(int arr[], int l, int r)
{
if (l < r) {
// Find the middle point
int m = l + (r - l) / 2;

// Sort first and second halves


sort(arr, l, m);
sort(arr, m + 1, r);

// Merge the sorted halves


merge(arr, l, m, r);
}
}

/* A utility function to print array of size n */


static void printArray(int arr[])
{
int n = arr.length;

40
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}

// Driver code
public static void main(String args[])
{
int arr[] = { 12, 11, 13, 5, 6, 7 };

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

MergeSort ob = new MergeSort();


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

System.out.println("\nSorted array");
printArray(arr);
}
}

OUTPUT:

Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13

RESULT :
Thus the program to implement Merge sort was implemented and successfully
executed.
41
EX.NO: Implement 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.
DATE:

Aim
To write a Java program to create a Quick Sort

ALGORITHM
Pseudo Code for Quick Sort:
/* low –> Starting index, high –> Ending index */
quickSort(arr[], low, high) {
if (low < high) {
/* pi is partitioning index, arr[pi] is now at right place */
pi = partition(arr, low, high);
quickSort(arr, low, pi – 1); // Before pi
quickSort(arr, pi + 1, high); // After pi
}
}
Pseudo code for partition():
/* This function takes last element as pivot, places the pivot element at its correct position in sorted array,
and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */
partition (arr[], low, high)
{
// pivot (Element to be placed at right position)
pivot = arr[high];
i = (low – 1) // Index of smaller element and indicates the
// right position of pivot found so far
for (j = low; j <= high- 1; j++){
// If current element is smaller than the pivot
if (arr[j] < pivot){
i++; // increment index of smaller element
swap arr[i] and arr[j]
}
}
swap arr[i + 1] and arr[high])
return (i + 1)
}

42
PROGRAM:

// Java implementation of QuickSort


import java.io.*;

class GFG {

// A utility function to swap two elements


static void swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

// This function takes last element as pivot,


// places the pivot element at its correct position
// in sorted array, and places all smaller to left
// of pivot and all greater elements to right of pivot
static int partition(int[] arr, int low, int high)
{
// Choosing the pivot
int pivot = arr[high];

// Index of smaller element and indicates


// the right position of pivot found so far
int i = (low - 1);

for (int j = low; j <= high - 1; j++) {

// If current element is smaller than the pivot


if (arr[j] < pivot) {

// Increment index of smaller element


i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
return (i + 1);
}

// The main function that implements QuickSort


// arr[] --> Array to be sorted,
// low --> Starting index,
// high --> Ending index
static void quickSort(int[] arr, int low, int high)
{
if (low < high) {

// pi is partitioning index, arr[p]

43
// is now at right place
int pi = partition(arr, low, high);

// Separately sort elements before


// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
// To print sorted array
public static void printArr(int[] arr){
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
}
// Driver Code
public static void main(String[] args)
{
int[] arr = { 10, 7, 8, 9, 1, 5 };
int N = arr.length;

// Function call
quickSort(arr, 0, N - 1);
System.out.println("Sorted array:");
printArr(arr);
}
}

OUTPUT:

Sorted array:
1 5 7 8 9 10

RESULT :
Thus the program to implement Quick sort was implemented and successfully
executed.

44
EX.NO:
Implement N Queens problem using
DATE: Backtracking

Aim
To write a Java program to Implement N Queens problem using Backtracking.

ALGORITHM

1. Initialize an empty chessboard of size NxN.


2. Start with the leftmost column and place a queen in the first row of that column.
3. Move to the next column and place a queen in the first row of that column.
4. Repeat step 3 until either all N queens have been placed or it is impossible to place a queen in the current
column without violating the rules of the problem.
5. If all N queens have been placed, print the solution.
6. If it is not possible to place a queen in the current column without violating the rules of the problem,
backtrack to the previous column.
7. Remove the queen from the previous column and move it down one row.
8. Repeat steps 4-7 until all possible configurations have been tried.

PROGRAM:

// Java program to solve N Queen Problem using backtracking

public class NQueenProblem {


final int N = 4;

// A utility function to print solution


void printSolution(int board[][])
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (board[i][j] == 1)
System.out.print("Q ");
else
System.out.print(". ");
}
System.out.println();
}
}

// A utility function to check if a queen can


// be placed on board[row][col]. Note that this
// function is called when "col" queens are already
// placeed in columns from 0 to col -1. So we need
// to check only left side for attacking queens
45
boolean isSafe(int board[][], int row, int col)
{
int i, j;

// Check this row on left side


for (i = 0; i < col; i++)
if (board[row][i] == 1)
return false;

// Check upper diagonal on left side


for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j] == 1)
return false;

// Check lower diagonal on left side


for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j] == 1)
return false;

return true;
}

// A recursive utility function to solve N


// Queen problem
boolean solveNQUtil(int board[][], int col)
{
// Base case: If all queens are placed
// then return true
if (col >= N)
return true;

// Consider this column and try placing


// this queen in all rows one by one
for (int i = 0; i < N; i++) {

// Check if the queen can be placed on


// board[i][col]
if (isSafe(board, i, col)) {

// Place this queen in board[i][col]


board[i][col] = 1;

// Recur to place rest of the queens


if (solveNQUtil(board, col + 1) == true)
return true;

// If placing queen in board[i][col]


// doesn't lead to a solution then
// remove queen from board[i][col]
board[i][col] = 0; // BACKTRACK
}

46
}

// If the queen can not be placed in any row in


// this column col, then return false
return false;
}

// This function solves the N Queen problem using


// Backtracking. It mainly uses solveNQUtil () to
// solve the problem. It returns false if queens
// cannot be placed, otherwise, return true and
// prints placement of queens in the form of 1s.
// Please note that there may be more than one
// solutions, this function prints one of the
// feasible solutions.
boolean solveNQ()
{
int board[][] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };

if (solveNQUtil(board, 0) == false) {
System.out.print("Solution does not exist");
return false;
}

printSolution(board);
return true;
}

// Driver program to test above function


public static void main(String args[])
{
NQueenProblem Queen = new NQueenProblem();
Queen.solveNQ();
}
}

OUTPUT:

. . Q .
Q . . .
. . . Q
. Q . .
RESULT :
Thus the program to implement N-Queen’s Problem was implemented and successfully
executed.
47
EX.NO: Implement any scheme to find the optimal
solution for the Traveling Salesperson
DATE:
problem and then solve the same problem
instance using any approximation algorithm
and determine the error in the approximation.
Aim
To write a Java program to create a optimal solution for the Traveling Salesperson problem

Description:

The nearest neighbour algorithm was one of the first algorithms used to determine a solution to the travelling
salesman problem. In it, the salesman starts at a random city and repeatedly visits the nearest city until all have
been visited. It quickly yields a short tour, but usually not the optimal one.

Algorithm
1. Start on an arbitrary vertex as current vertex.
2. Find out the shortest edge connecting current vertex and an unvisited vertex V.
3. Set current vertex to V.
4. Mark V as visited.
5. If all the vertices in domain are visited, then terminate.
6. Go to step 2.
7. The sequence of the visited vertices is the output of the algorithm.

Program:

#include<stdio.h>
int a[10][10],n,visit[10];
int cost_opt=0,cost_apr=0;
int least_apr(int c);
int least_opt(int c);

void mincost_opt(int city)


{
int i,ncity;
visit[city]=1;
printf("%d-->",city);
ncity=least_opt(city);
if(ncity==999)
{
ncity=1;
printf("%d",ncity);
cost_opt+=a[city][ncity];
return;
}
mincost_opt(ncity);
}

48
void mincost_apr(int city)
{
int i,ncity;
visit[city]=1;
printf("%d-->",city);
ncity=least_apr(city);
if(ncity==999)
{
ncity=1;
printf("%d",ncity);
cost_apr+=a[city][ncity];
return;
}
mincost_apr(ncity);
}

int least_opt(int c)
{
int i,nc=999;
int min=999,kmin=999;
for(i=1;i<=n;i++)
{
if((a[c][i]!=0)&&(visit[i]==0))
if(a[c][i]<min)
{
min=a[i][1]+a[c][i];
kmin=a[c][i];
nc=i;
}
}
if(min!=999)
cost_opt+=kmin;
return nc;
}

int least_apr(int c)
{
int i,nc=999;
int min=999,kmin=999;
for(i=1;i<=n;i++)
{
if((a[c][i]!=0)&&(visit[i]==0))
if(a[c][i]<kmin)
{
min=a[i][1]+a[c][i];
kmin=a[c][i];
nc=i;
}
}
49
if(min!=999)
cost_apr+=kmin;
return nc;
}
void main()
{
int i,j;
printf("Enter No. of cities:\n");
scanf("%d",&n);

printf("Enter the cost matrix\n");


for(i=1;i<=n;i++)
{
printf("Enter elements of row:%d\n",i );
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
visit[i]=0;
}
printf("The cost list is \n");
for(i=1;i<=n;i++)
{
printf("\n\n");
for(j=1;j<=n;j++)
printf("\t%d",a[i][j]);
}
printf("\n\n Optimal Solution :\n");
printf("\n The path is :\n");
mincost_opt(1);
printf("\n Minimum cost:");
printf("%d",cost_opt);

printf("\n\n Approximated Solution :\n");


for(i=1;i<=n;i++)
visit[i]=0;
printf("\n The path is :\n");
mincost_apr(1);
printf("\nMinimum cost:");
printf("%d",cost_apr);
printf("\n\nError in approximation is approximated solution/optimal solution=%f",
(float)cost_apr/cost_opt);
}

50
OUTPUT 1 :

Enter No. of cities:


4
Enter the cost matrix
Enter elements of row:1
0136
Enter elements of row:2
1023
Enter elements of row:3
3201
Enter elements of row:4
6310

The cost list is

0 1 3 6

1 0 2 3

3 2 0 1

6 3 1 0

Optimal Solution :

The path is :
1-->2-->4-->3-->1
Minimum cost:8

Approximated Solution :

The path is :
1-->2-->3-->4-->1
Minimum cost:10

Error in approximation is approximated solution/optimal solution=1.250000

RESULT :
Thus the program to implement Approximation algorithm was implemented and
successfullyexecuted.

51
EX.NO: Implement randomized algorithms for finding
the kth smallest number. The programs can be
DATE:
implemented in C/C++/JAVA/ Python.

Aim
To write a Java program to Implement randomized algorithms for finding the kth smallest number

ALGORITHM

1. Select a random element from an array as a pivot.


2. Then partition to the array around the pivot, its help to all the smaller elements were placed before the
pivot and all greater elements are placed after the pivot.
3. then Check the position of the pivot. If it is the kth element then return it.
4. If it is less than the kth element then repeat the process of the subarray.
5. If it is greater than the kth element then repeat the process of the left subarray.

PROGRAM:
// Java program to find k'th smallest element in expected
// linear time
class KthSmallst
{
// This function returns k'th smallest element in arr[l..r]
// using QuickSort based method. ASSUMPTION: ALL ELEMENTS
// IN ARR[] ARE DISTINCT
int kthSmallest(int arr[], int l, int r, int k)
{
// If k is smaller than number of elements in array
if (k > 0 && k <= r - l + 1)
{
// Partition the array around a random element and
// get position of pivot element in sorted array
int pos = randomPartition(arr, l, r);

// If position is same as k
if (pos-l == k-1)
return arr[pos];

// If position is more, recur for left subarray


if (pos-l > k-1)
return kthSmallest(arr, l, pos-1, k);

// Else recur for right subarray


return kthSmallest(arr, pos+1, r, k-pos+l-1);
}

// If k is more than number of elements in array


return Integer.MAX_VALUE;
52
}

// Utility method to swap arr[i] and arr[j]


void swap(int arr[], int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

// Standard partition process of QuickSort(). It considers


// the last element as pivot and moves all smaller element
// to left of it and greater elements to right. This function
// is used by randomPartition()
int partition(int arr[], int l, int r)
{
int x = arr[r], i = l;
for (int j = l; j < r; j++)
{
if (arr[j] <= x)
{
swap(arr, i, j);
i++;
}
}
swap(arr, i, r);
return i;
}

// Picks a random pivot element between l and r and


// partitions arr[l..r] arount the randomly picked
// element using partition()
int randomPartition(int arr[], int l, int r)
{
int n = r - l + 1;
int pivot = (int)(Math.random() * (n - 1));
swap(arr, l + pivot, r);
return partition(arr, l, r);
}

// Driver method to test above


public static void main(String args[])
{
KthSmallst ob = new KthSmallst();
int arr[] = {12, 3, 5, 7, 4, 19, 26};
int n = arr.length,k = 3;
System.out.println("K'th smallest element is "+
ob.kthSmallest(arr, 0, n-1, k));
}
}

53
OUTPUT:

K'th smallest element is 5

RESULT :
Thus the program was implemented and successfully executed.

54

You might also like