0% found this document useful (0 votes)
176 views21 pages

Lab Manual: Meerut Institute of & Technology, Meerut

The document contains a lab manual for the Design and Analysis of Algorithms lab course at the Meerut Institute of Engineering & Technology. It includes 11 programming assignments involving algorithms such as Quick Sort, Counting Sort, Merge Sort, Warshall's algorithm for finding all pairs shortest paths, Knapsack problem, shortest path algorithms, minimum spanning trees, and the travelling salesperson problem. The lab aims to help students design and analyze various sorting and optimization algorithms and identify the appropriate algorithm to solve different problems.

Uploaded by

rahulprajap
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
176 views21 pages

Lab Manual: Meerut Institute of & Technology, Meerut

The document contains a lab manual for the Design and Analysis of Algorithms lab course at the Meerut Institute of Engineering & Technology. It includes 11 programming assignments involving algorithms such as Quick Sort, Counting Sort, Merge Sort, Warshall's algorithm for finding all pairs shortest paths, Knapsack problem, shortest path algorithms, minimum spanning trees, and the travelling salesperson problem. The lab aims to help students design and analyze various sorting and optimization algorithms and identify the appropriate algorithm to solve different problems.

Uploaded by

rahulprajap
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

MEERUT INSTITUTE OF ENGINEERING & TECHNOLOGY, MEERUT

N.H. 58, Delhi-Roorkee Highway, Baghpat Road Bypass Crossing, Meerut-250005

Department of Information Technology


B. Tech. (Session 2020-21)

Lab Manual

Design And Analysis of Algorithm Lab

(RCS-552)

Submitted to: Submitted by:


Dr. Wakarahmad Robin Chauhan
IT (G2)
1900680130038
MEERUT INSTITUTE OF ENGINEERING & TECHNOLOGY, MEERUT
N.H. 58, Delhi-Roorkee Highway, Baghpat Road Bypass Crossing, Meerut-250005

Computer Science & Engineering Department


B. Tech. 3rd Year/ 5th Semester
(Session: 2018 – 19)

DAA Lab. (RCS-552)

1. Write a program to implement Quick Sort on an unsortedarray.

2. Write a program to implement Counting Sort on an unsortedarray.

3. Write a program to implement Merge Sort on an unsortedarray.

4. Write a program to implement Warshall algorithm.

5. Write a program to Knapsack problem.

6. Write a program to implement Shortest paths algorithm.

7. Write a program to Minimum Cost Spanning Tree.

8. Write a program to implement Tree Traversals.

9. Write a program to Sum of Subsets Problem.

10. Write a program to Travelling Sales Person Problem.

11. Write a program to All Pairs Shortest Paths.

………………………………………. …………………………………. ………………………………….


Signature of Faculty Lab In-charge Signature of Subject Head of Department
Coordinator
Lab Course Outcome

 Design and implement various Linear and Polynomial Time Sortingalgorithms.

 Employ various design strategies for problem solving and Implement various algorithms in ahigh
level language.

 Synthesize divide-and-conqueralgorithms.

 Identify the problem given and design the algorithm using various algorithm designtechniques.

 Analyze the performance of variousalgorithms.

 Compare the performance of different algorithms for sameproblem.


EXPERIMENT-1
Object:Write a program to implement Quick Sort on an unsorted array.

PROGRAM:

#include <bits/stdc++.h>
using namespace std;
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}

int partition (int arr[], int low, int high)


{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element and indicates the right position of pivot found so far

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


{
if (arr[j] < pivot)
{
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}

void quickSort(int arr[], int low, int high)


{
if (low < high)
{

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


quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
void printArray(int arr[], int size)
{
int i;
for (i = 0; i< size; i++)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
cout << "Sorted array: \n";
printArray(arr, n);
return 0;
}

OUTPUT :
Sorted array:
1 5 7 8 9 10

EXPERIMENT- 2

Object:Write a program to implement Counting Sort on an unsortedarray.

PROGRAM :

using System;

class GFG {

static void countsort(char[] arr)


{
int n = arr.Length;
char[] output = new char[n];
int[] count = new int[256];

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


count[i] = 0;

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


++count[arr[i]];
for (int i = 1; i <= 255; ++i)
count[i] += count[i - 1];
for (int i = n - 1; i >= 0; i--) {
output[count[arr[i]] - 1] = arr[i];
--count[arr[i]];
}
for (int i = 0; i < n; ++i)
arr[i] = output[i];
}

public static void Main()


{
char[] arr = { ‘c’, ‘o’, ‘u’, ‘n’, ‘t’, ‘i’, ‘n’, ‘g’, ‘s’, ‘o’, ‘r’, ‘t’ };

countsort(arr);

Console.Write("Sorted character array is ");


for (int i = 0; i < arr.Length; ++i)
Console.Write(arr[i]);
}
}

OUTPUT
Sorted character array is cginnoorsttu

EXPERIMENT-3
Object: Write a program to implement Merge Sort on an unsortedarray

PROGRAM:
using System;
class MergeSort
{
void merge(int[] arr, int l, int m, int r)
{

int n1 = m - l + 1;
int n2 = r - m;
int[] L = new int[n1];
int[] R = new int[n2];
int i, j;

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


L[i] = arr[l + i];
for (j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
i = 0;
j = 0;
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++;
}

while (i < n1)


{
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void sort(int[] arr, int l, int r)
{
if (l < r) {
int m = l+ (r-l)/2;
sort(arr, l, m);
sort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
static void printArray(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n; ++i)
Console.Write(arr[i] + " ");
Console.WriteLine();
}
public static void Main(String[] args)
{
int[] arr = { 12, 11, 13, 5, 6, 7 };
Console.WriteLine("Given Array");
printArray(arr);
MergeSort ob = new MergeSort();
ob.sort(arr, 0, arr.Length - 1);
Console.WriteLine("\nSorted array");
printArray(arr);
}
}

OUTPUT:
Given array is 23 45 6 42 8 3
Sorted array is 3 6 8 23 42 45
EXPERIMENT -4
Object: Write a program to implement Warshall algorithm

PROGRAM:

using System;
public class AllPairShortestPath
{
readonly static int INF = 99999, V = 4;

void floydWarshall(int[,] graph)


{
int[,] dist = new int[V, V];
int i, j, k;
for (i = 0; i < V; i++) {
for (j = 0; j < V; j++) {
dist[i, j] = graph[i, j];
}
}
for (k = 0; k < V; k++)
{
for (i = 0; i < V; i++)
{
for (j = 0; j < V; j++)
{

if (dist[i, k] + dist[k, j] < dist[i, j])


{
dist[i, j] = dist[i, k] + dist[k, j];
}
}
}
}

printSolution(dist);
}

void printSolution(int[,] dist)


{
Console.WriteLine("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) {
Console.Write("INF ");
} else {
Console.Write(dist[i, j] + " ");
}
}
Console.WriteLine();
}
}
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();
a.floydWarshall(graph);
}
}

OUTPUT :
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

EXPERIMENT -5
Object: Write a program to Knapsack problem

PROGRAM:

using System ;

class GFG {

static int max(int a, int b)


{
return (a > b) ? a : b;
}

static void printknapSack(int W, int []wt,


int []val, int n)
{
int i, w;
int [,]K = new int[n + 1,W + 1];

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


for (w = 0; w <= W; w++) {
if (i == 0 || w == 0)
K[i,w] = 0;
else if (wt[i - 1] <= w)
K[i,w] = Math.Max(val[i - 1] +
K[i - 1,w - wt[i - 1]], K[i - 1,w]);
else
K[i,w] = K[i - 1,w];
}
}

int res = K[n,W];


Console.WriteLine(res);

w = W;
for (i = n; i> 0 && res > 0; i--) {

if (res == K[i - 1,w])


continue;
else {

Console.Write(wt[i - 1] + " ");

res = res - val[i - 1];


w = w - wt[i - 1];
}
}
}

public static void Main()


{
int []val = { 60, 100, 120 };
int []wt = { 10, 20, 30 };
int W = 50;
int n = val.Length;

printknapSack(W, wt, val, n);


}
}

OUTPUT:

220
20 30
EXPERIMENT-6
Object:Write a program to implement Shortest paths algorithm

PROGRAM:
using System;
using System.Collections.Generic;
class pathUnweighted{

public static void Main(String []args)


{
int v = 8;
List<List<int>> adj =new List<List<int>>(v);
for (int i = 0; i< v; i++)
{
adj.Add(new List<int>());
}

addEdge(adj, 0, 1);
addEdge(adj, 0, 3);
addEdge(adj, 1, 2);
addEdge(adj, 3, 4);
addEdge(adj, 3, 7);
addEdge(adj, 4, 5);
addEdge(adj, 4, 6);
addEdge(adj, 4, 7);
addEdge(adj, 5, 6);
addEdge(adj, 6, 7);
int source = 0, dest = 7;
printShortestDistance(adj, source,dest, v);
}
private static void addEdge(List<List<int>> adj,int i, int j)
{
adj[i].Add(j);
adj[j].Add(i);
}
private static void printShortestDistance(List<List<int>> adj,int s, int dest, int v)
{
int []pred = new int[v];
int []dist = new int[v];

if (BFS(adj, s, dest,v, pred, dist) == false)


{
Console.WriteLine("Given source and destination" +"are not connected");
return;
}
List<int> path = new List<int>();
int crawl = dest;
path.Add(crawl);

while (pred[crawl] != -1)


{
path.Add(pred[crawl]);
crawl = pred[crawl];
}
Console.WriteLine("Shortest path length is: " +dist[dest]);

Console.WriteLine("Path is ::");
for (int i = path.Count - 1;
i >= 0; i--)
{
Console.Write(path[i] + " ");
}
}
private static bool BFS(List<List<int>> adj,int src, int dest,int v, int []pred,int []dist)
{
List<int> queue = new List<int>();
bool []visited = new bool[v];
for (int i = 0; i < v; i++)
{
visited[i] = false;
dist[i] = int.MaxValue;
pred[i] = -1;
}
visited[src] = true;
dist[src] = 0;
queue.Add(src);
while (queue.Count != 0)
{
int u = queue[0];
queue.RemoveAt(0);

for (int i = 0;
i < adj[u].Count; i++)
{
if (visited[adj[u][i]] == false)
{
visited[adj[u][i]] = true;
dist[adj[u][i]] = dist[u] + 1;
pred[adj[u][i]] = u;
queue.Add(adj[u][i]);

if (adj[u][i] == dest)
return true;
}
}
}
return false;
}
}

OUTPUT:Shortest path length is : 2


Path is::
037

EXPERIMENT-7
Object: Write a program to Minimum Cost Spanning Tree.

PROGRAM:

#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#define V 5
int minKey(int key[], bool mstSet[])
{
// Initialize min value
int min = INT_MAX, min_index;

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


if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;

return min_index;
}
int printMST(int parent[], int graph[V][V])
{
printf("Edge \tWeight\n");
for (int i = 1; i< V; i++)
printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
}
void primMST(int graph[V][V])
{

bool mstSet[V];
for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;

key[0] = 0;
parent[0] = -1;
for (int count = 0; count < V - 1; count++) {

int u = minKey(key, mstSet);


mstSet[u] = true;
for (int v = 0; v < V; v++)
if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}

// print the constructed MST


printMST(parent, graph);
}

// driver program to test above function


int main()
{
/* Let us create the following graph
23
(0)--(1)--(2)
|/\|
6| 8/ \5 |7
|/ \|
(3)-------(4)
9 */
int graph[V][V] = { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };

// Print the solution


primMST(graph);

return 0;
}

OUTPUT:

Edge Weight
0-1 2
1-2 3
0-3 6
1-4 5
EXPERIMENT-8
Object: Write a program to implement Tree Traversals.

PROGRAM:

#include <stdio.h>
#include <stdlib.h>

struct node {
int data;
struct node* left;
struct node* right;
};

struct node* newNode(int data)


{
struct node* node
= (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;

return (node);
}
void printPostorder(struct node* node)
{
if (node == NULL)
return;
printPostorder(node->left);
printPostorder(node->right);
printf("%d ", node->data);
}

void printInorder(struct node* node)


{
if (node == NULL)
return;
printInorder(node->left);
printf("%d ", node->data);
printInorder(node->right);
}

void printPreorder(struct node* node)


{
if (node == NULL)
return;
printf("%d ", node->data);
printPreorder(node->left);
printPreorder(node->right);
}
int main()
{
struct node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);

printf("\nPreorder traversal of binary tree is \n");


printPreorder(root);

printf("\nInorder traversal of binary tree is \n");


printInorder(root);

printf("\nPostorder traversal of binary tree is \n");


printPostorder(root);

getchar();
return 0;
}

OUTPUT:
Preorder traversal of binary tree is
12453
Inorder traversal of binary tree is
42513
Postorder traversal of binary tree is
45231

EXPERIMENT-9
Object: Write a program to Sum of Subsets Problem
PROGRAM:
using System;
class GFG
{
static int subsetSum(int []a, int n, int sum)
{

int [,]tab = new int[n + 1,sum + 1];


for (int i = 1; i <= n; i++) {
for (int j = 1; j <= sum; j++) {
tab[i,j] = -1;
}
}
if (sum == 0)
return 1;

if (n <= 0)
return 0;
if (tab[n - 1,sum] != -1)
return tab[n - 1,sum];
if (a[n - 1] > sum)
return tab[n - 1,sum]
= subsetSum(a, n - 1, sum);
else {
if (subsetSum(a, n - 1, sum) != 0
|| subsetSum(a, n - 1, sum - a[n - 1])!= 0) {
return tab[n - 1,sum] = 1;
}
else
return tab[n - 1,sum] = 0;
}
}
public static void Main(String[] args)
{

int n = 5;
int []a = { 1, 5, 3, 7, 4 };
int sum = 12;

if (subsetSum(a, n, sum) != 0) {
Console.Write("YES\n");
}
else
Console.Write("NO\n");
}
}

OUTPUT: Yes
EXPERIMENT-10
Object: Write a program to Travelling Sales Person Problem.

PROGRAM:

#include<stdio.h>
#include<stdlib.h>
 intsmallest(int);
 voidminimumcost(int);
 
inta[10][10], visited[10];
 intn, cost=0;
 voidmain()
{
        inti, j;
  printf("enter the no. of cities\n");
  scanf("%d",&n);
  printf("enter matrix\n");
  for(i=0;i<n;i++)
        {
                for(j=0;j>n;j++)
                {
                        scanf("%d",&a[i][j]);
                }
                visited[i] = 0;
    }
 
        printf("the path is\n");
 minimumcost(0);
  printf("minimum cost = %d",cost);
}
 
voidminimumcost(intcity)
 
{
        inti, nextcity;
  visited[city] = 1;
  printf("%d-->",city+1);
         
nextcity = smallest(city);
 
        if(nextcity == 999)
        {
                nextcity = 0;
 printf("%d",nextcity+1);
 
                cost = cost + a[city][nextcity];
  return;
        }
          minimumcost(nextcity);
}
 
intsmallest(intc)
 
{
        inti, nc=999;
        intminimum = 999, dmin;
 
        for(i=0;i<n;i++)
        {
                if(a[c][i] != 0&& visited[i] == 0)
                {
                        if(a[c][i] + a[i][c] < minimum)
                        {
                                minimum = a[i][0] + a[c][i];
 
                                dmin = a[c][i];
 
                                nc = i;
                        }
                }
        }
 
        if(minimum != 999)
        {
                cost += dmin;
        }
        returnnc;
 
}

OUTPUT:
enter the no. of cities
4

enter matrix
0
1
5
7
4
0
6
5
7
8
0
1
7
6
3
0

the path is
1-->2-->4-->3-->1

minimum cost = 16

EXPERIMENT-11
Object: Write a program to All Pairs Shortest Paths.

PROGRAM:
using System;
class GFG{

static readonly int INF = 99999;


static int floyd_warshall(int[,] graph,int V)
{
int [,]dist = new int[V, V];
int i, j, k;
for (i = 0; i < V; i++)
{
for (j = 0; j < V; j++)
{
dist[i, j] = graph[i, j];
}
}
for (k = 0; k < V; k++)
{
for (i = 0; i < V; i++)
{
for (j = 0; j < V; j++)
{
if (dist[i, k] + dist[k, j] <dist[i, j])
{
dist[i, j] = dist[i, k] +dist[k, j];
}
}
}
}
int sum = 0;
for (i = 0; i < V; i++)
{
for (j = i + 1; j < V; j++)
{
sum += dist[i, j];
}
}
return sum;
}
static int sumOfshortestPath(int N, int E, int [,]edges)
{
int [,]g = new int[N, N];

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


{
for (int j = 0; j < N; j++)
{
g[i, j] = INF;
}
}
for (int i = 0; i < E; i++)
{

int u = edges[i, 0];


int v = edges[i, 1];
int w = edges[i, 2];
g[u, v] = w;
g[v, u] = w;
}
return floyd_warshall(g, N);
}
public static void Main(String[] args)
{
int N = 4;
int E = 3;
int [,]Edges = {{0, 1, 1},{1, 2, 2},{2, 3, 3}};
Console.Write(sumOfshortestPath(N, E, Edges));
}
}

OUTPUT: 20

You might also like