Algorithms Lab Updated
Algorithms Lab Updated
S ENGINEERING COLLEGE
Gummidipoondi Taluk,
Thiruvallur District-601206
NAME : ………………………………………………
REG NO : ……………………………………….
DEPARTMENT : ..…………………………………………….
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 : …………………………………………
YEAR/SEM : ………………………………………
REGISTER NUMBER :
Certified that this is the Bonafide record of practical work done by the aforesaid student in the
during the year
.
2
INDEX
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 3: If key element is found, return the index position of the array element
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:
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:
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
PROGRAM:
import java.io.*;
class GFG {
public static void main(String[] args)
{
9
}
public static void stringMatch(String text, String pattern)
{
int k = 0, i = 0, j = 0;
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.
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.
PROGRAM:
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] + " ");
}
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);
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>();
}
{
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:
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 2: Push the starting node A on the stack and set its STATUS = 2 (waiting state)
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[];
Iterator<Integer> it = adj[vertex].listIterator();
while (it.hasNext()) {
int n = it.next();
if (!visited[n])
DFS(n);
}
}
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);
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
Step2: All the nodes must be initialized with the "infinite" (a big number) distance. The starting node must be
initialized with zero.
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.*;
// 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 } };
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.*;
// 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 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 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
// 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];
}
}
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:
class AllPairShortestPath {
final static int INF = 99999, V = 4;
int i, j, k;
// 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 } };
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:
class GraphClosure
{
final static int V = 4; //Number of vertices in a graph
// Driver Code
public static void main (String[] args)
{
/* Let us create the following weighted graph
10
35
(0)------->(3)
| /|\
5| |
| |1
\|/ |
(1)------->(2)
3 */
OUTPUT:
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:
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;
}
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:
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);
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:
class GFG {
43
// is now at right place
int pi = partition(arr, low, high);
// 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
PROGRAM:
return true;
}
46
}
if (solveNQUtil(board, 0) == false) {
System.out.print("Solution does not exist");
return false;
}
printSolution(board);
return true;
}
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);
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);
50
OUTPUT 1 :
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
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
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];
53
OUTPUT:
RESULT :
Thus the program was implemented and successfully executed.
54