0% found this document useful (0 votes)
19 views71 pages

Cs3401 - Algorithms Lab Manual

The CS3401 Algorithms syllabus outlines course objectives including understanding algorithm analysis, efficiency of graph algorithms, and various design techniques. It includes a list of experiments focusing on searching, sorting, graph algorithms, and state space search, along with expected course outcomes for students. Additionally, it discusses the characteristics, types, advantages, and disadvantages of algorithms, as well as guidelines for designing them.
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)
19 views71 pages

Cs3401 - Algorithms Lab Manual

The CS3401 Algorithms syllabus outlines course objectives including understanding algorithm analysis, efficiency of graph algorithms, and various design techniques. It includes a list of experiments focusing on searching, sorting, graph algorithms, and state space search, along with expected course outcomes for students. Additionally, it discusses the characteristics, types, advantages, and disadvantages of algorithms, as well as guidelines for designing them.
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/ 71

| CS3401 Algorithms

CS3401 ALGORITHMS
(R2021)

SYLLABUS

COURSE OBJECTIVES:
The student should be made to:
 To understand and apply the algorithm analysis techniques on searching and sorting
algorithms.
 To critically analyze the efficiency of graph algorithms.
 To understand different algorithm design techniques.
 To solve programming problems using state space tree.
 To understand the concepts behind NP Completeness, Approximation algorithms and
randomized algorithms.

LIST OF EXPERIMENTS
Searching and Sorting Algorithms
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.
Graph Algorithms
1. Develop a program to implement graph traversal using Breadth First Search.
2. Develop a program to implement graph traversal using Depth First Search.
3. From a given vertex in a weighted connected graph, develop a program to find the shortest
paths to other vertices using Dijkstra’s algorithm.
4. Find the minimum cost spanning tree of a given undirected graph using Prim’s algorithm.
5. Implement Floyd’s algorithm for the All-Pairs- Shortest-Paths problem.
6. Compute the transitive closure of a given directed graph using Warshall's algorithm.
Algorithm Design Techniques
1. Develop a program to find out the maximum and minimum numbers in a given list of n
numbers using the divide and conquer technique.
2. 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
1. Implement N-Queens problem using Backtracking.
Approximation Algorithms Randomized Algorithms
1. 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.

GRT Institute of Engineering and Technology, Tiruttani P a g e |1


| CS3401 Algorithms

2. Implement randomized algorithms for finding the kth smallest number.


The programs can be implemented in C/C++/JAVA/ Python.
COURSE OUTCOMES:
At the end of the course, the students will be able to:
CO1: Implement and analyze various searching and sorting algorithms.
CO2: Implement various graph algorithms.
CO3: Develop simple programs using divide-and-conquer technique and analyze its efficiency.
CO4: Implement N-Queens problem using Backtracking.
CO5: Develop simple programs using Approximation/Randomized algorithms.

CO-PO Mapping Matrix:


Course
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
Outcome
CO1 2 1 3 2 - - - - 2 1 2 3 2 1 1
CO2 2 1 1 1 1 - - - 1 3 3 3 2 2 2
CO3 1 3 3 3 1 - - - 1 2 1 2 2 2 3
CO4 1 2 2 3 - - - - 2 3 3 1 2 1 2
CO5 1 2 3 2 3 - - - 3 1 3 3 1 1 2
AVG. 1.4 1.8 2.4 2.2 1.7 - - - 1.8 2 2.4 2.4 1.8 1.4 2

EVALUATION OF LAB REPORT:

Marks Marks
Evaluation Parameters
Allotted Awarded
Aim & Algorithm: 20
Program: 30
Implementation & Result: 30
Viva Voce: 10
Record: 10
Total: 100

GRT Institute of Engineering and Technology, Tiruttani P a g e |2


| CS3401 Algorithms

CS3401 ALGORITHMS
Ex. Page Faculty
Date INDEX Marks
No. Number Signature
1 LINEAR SEARCH

2 BINARY SEARCH

3 NAIVE PATTERN MATCHING

4a INSERTION SORT

4b HEAP SORT

5 BREADTH FIRST SEARCH

6 DEPTH FIRST SEARCH

7 DIJKSTRA’S ALGORITHM

8 PRIM’S ALGORITHM

9 FLOYD’S ALGORITHM

10 WARSHALL’S ALGORITHM
FINDING MIN AND MAX USING
11
DIVIDE AND CONQUER
12a MERGE SORT

12b QUICK SORT


N-QUEENS PROBLEM USING
13
BACKTRACKING
14 TRAVELING SALESPERSON PROBLEM

15 FINDING KTH SMALLEST ELEMENT

CONTENT BEYOND SYLLABUS

16 FINDING CYCLE IN A DIRECTED GRAPH `


JOB ASSIGNMENT PROBLEM USING
17
BRANCH AND BOUND

GRT Institute of Engineering and Technology, Tiruttani P a g e |3


| CS3401 Algorithms

INTRODUCTION TO ALGORITHMS
What is an Algorithm?

Algorithm Basics:

The word Algorithm means ” A set of finite rules or instructions to be followed in calculations or
other problem-solving operations ” Or ” A procedure for solving a mathematical problem in a finite
number of steps that frequently involves recursive operations”.
Therefore Algorithm refers to a sequence of finite steps to solve a particular problem.

Use of the Algorithms:-


Algorithms play a crucial role in various fields and have many applications. Some of the key areas
where algorithms are used include:
Computer Science: Algorithms form the basis of computer programming and are used to solve
problems ranging from simple sorting and searching to complex tasks such as artificial intelligence
and machine learning.
Mathematics: Algorithms are used to solve mathematical problems, such as finding the optimal
solution to a system of linear equations or finding the shortest path in a graph.
Operations Research: Algorithms are used to optimize and make decisions in fields such as
transportation, logistics, and resource allocation.
Artificial Intelligence: Algorithms are the foundation of artificial intelligence and machine
learning, and are used to develop intelligent systems that can perform tasks such as image
recognition, natural language processing, and decision-making.
Data Science: Algorithms are used to analyze, process, and extract insights from large amounts of
data in fields such as marketing, finance, and healthcare.
These are just a few examples of the many applications of algorithms. The use of algorithms is
continually expanding as new technologies and fields emerge, making it a vital component of
modern society.

Algorithms can be simple and complex depending on what you want to achieve.

It can be understood by taking the example of cooking a new recipe. To cook a new recipe, one
reads the instructions and steps and executes them one by one, in the given sequence. The result
thus obtained is the new dish is cooked perfectly. Every time you use your phone, computer, laptop,
or calculator you are using Algorithms. Similarly, algorithms help to do a task in programming to
get the expected output.
The Algorithms designed are language-independent, i.e. they are just plain instructions that can be
implemented in any language, and yet the output will be the same, as expected.

GRT Institute of Engineering and Technology, Tiruttani P a g e |4


| CS3401 Algorithms

What is the need for algorithms?


 Algorithms are necessary for solving complex problems efficiently and effectively.
 They help to automate processes and make them more reliable, faster, and easier to
perform.
 Algorithms also enable computers to perform tasks that would be difficult or impossible for
humans to do manually.
 They are used in various fields such as mathematics, computer science, engineering,
finance, and many others to optimize processes, analyze data, make predictions, and
provide solutions to problems.

What are the Characteristics of an Algorithm?

As one would not follow any written instructions to cook the recipe, but only the standard one.
Similarly, not all written instructions for programming is an algorithms. In order for some
instructions to be an algorithm, it must have the following characteristics:
Clear and Unambiguous: The algorithm should be clear and unambiguous. Each of its steps
should be clear in all aspects and must lead to only one meaning.
Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined inputs. It may
or may not take input.
Well-Defined Outputs: The algorithm must clearly define what output will be yielded and it
should be well-defined as well. It should produce at least 1 output.
Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite time.
Feasible: The algorithm must be simple, generic, and practical, such that it can be executed with
the available resources. It must not contain some future technology or anything.
Language Independent: The Algorithm designed must be language-independent, i.e. it must be
just plain instructions that can be implemented in any language, and yet the output will be the same,
as expected.
Input: An algorithm has zero or more inputs. Each that contains a fundamental operator must
accept zero or more inputs.
Output: An algorithm produces at least one output. Every instruction that contains a fundamental
operator must accept zero or more inputs.

GRT Institute of Engineering and Technology, Tiruttani P a g e |5


| CS3401 Algorithms

Definiteness: All instructions in an algorithm must be unambiguous, precise, and easy to interpret.
By referring to any of the instructions in an algorithm one can clearly understand what is to be
done. Every fundamental operator in instruction must be defined without any ambiguity.
Finiteness: An algorithm must terminate after a finite number of steps in all test cases. Every
instruction which contains a fundamental operator must be terminated within a finite amount of
time. Infinite loops or recursive functions without base conditions do not possess finiteness.
Effectiveness: An algorithm must be developed by using very basic, simple, and feasible operations
so that one can trace it out by using just paper and pencil.
Properties of Algorithm:
 It should terminate after a finite time.
 It should produce at least one output.
 It should take zero or more input.
 It should be deterministic means giving the same output for the same input case.
 Every step in the algorithm must be effective i.e. every step should do some work.
Types of Algorithms:
There are several types of algorithms available. Some important algorithms are:
1. Brute Force Algorithm: It is the simplest approach for a problem. A brute force algorithm is the
first approach that comes to finding when we see a problem.
2. Recursive Algorithm: A recursive algorithm is based on recursion. In this case, a problem is
broken into several sub-parts and called the same function again and again.
3. Backtracking Algorithm: The backtracking algorithm basically builds the solution by searching
among all possible solutions. Using this algorithm, we keep on building the solution following
criteria. Whenever a solution fails we trace back to the failure point and build on the next solution
and continue this process till we find the solution or all possible solutions are looked after.
4. Searching Algorithm: Searching algorithms are the ones that are used for searching elements or
groups of elements from a particular data structure. They can be of different types based on their
approach or the data structure in which the element should be found.
5. Sorting Algorithm: Sorting is arranging a group of data in a particular manner according to the
requirement. The algorithms which help in performing this function are called sorting algorithms.
Generally sorting algorithms are used to sort groups of data in an increasing or decreasing manner.
6. Hashing Algorithm: Hashing algorithms work similarly to the searching algorithm. But they
contain an index with a key ID. In hashing, a key is assigned to specific data.
7. Divide and Conquer Algorithm: This algorithm breaks a problem into sub-problems, solves a
single sub-problem and merges the solutions together to get the final solution. It consists of the
following three steps:
 Divide
 Solve
 Combine
8. Greedy Algorithm: In this type of algorithm the solution is built part by part. The solution of the
next part is built based on the immediate benefit of the next part. The one solution giving the most
benefit will be chosen as the solution for the next part.
9. Dynamic Programming Algorithm: This algorithm uses the concept of using the already found
solution to avoid repetitive calculation of the same part of the problem. It divides the problem into
smaller overlapping subproblems and solves them.
10. Randomized Algorithm: In the randomized algorithm we use a random number so it gives
immediate benefit. The random number helps in deciding the expected outcome.

GRT Institute of Engineering and Technology, Tiruttani P a g e |6


| CS3401 Algorithms

Advantages of Algorithms:
 It is easy to understand.
 An algorithm is a step-wise representation of a solution to a given problem.
 In Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for
the programmer to convert it into an actual program.
Disadvantages of Algorithms:
 Writing an algorithm takes a long time so it is time-consuming.
 Understanding complex logic through algorithms can be very difficult.
 Branching and Looping statements are difficult to show in Algorithms(imp).

How to Design an Algorithm?


In order to write an algorithm, the following things are needed as a pre-requisite:

1. The problem that is to be solved by this algorithm i.e. clear problem definition.
2. The constraints of the problem must be considered while solving the problem.
3. The input to be taken to solve the problem.
4. The output to be expected when the problem is solved.
5. The solution to this problem is within the given constraints.

Then the algorithm is written with the help of the above parameters such that it solves the problem.

Example: Consider the example to add three numbers and print the sum.

Step 1: Fulfilling the pre-requisites


As discussed above, in order to write an algorithm, its pre-requisites must be fulfilled.
 The problem that is to be solved by this algorithm: Add 3 numbers and print their sum.
 The constraints of the problem that must be considered while solving the problem: The
numbers must contain only digits and no other characters.
 The input to be taken to solve the problem: The three numbers to be added.
 The output to be expected when the problem is solved: The sum of the three numbers
taken as the input i.e. a single integer value.
 The solution to this problem, in the given constraints: The solution consists of adding
the 3 numbers. It can be done with the help of ‘+’ operator, or bit-wise, or any other
method.

Step 2: Designing the algorithm


Now let’s design the algorithm with the help of the above pre-requisites:
Algorithm to add 3 numbers and print their sum:
1. START
2. Declare 3 integer variables num1, num2 and num3.
3. Take the three numbers, to be added, as inputs in variables num1, num2, and num3
respectively.
4. Declare an integer variable sum to store the resultant sum of the 3 numbers.
5. Add the 3 numbers and store the result in the variable sum.
6. Print the value of the variable sum
7. END
Step 3: Testing the algorithm by implementing it.
In order to test the algorithm, let’s implement it in C/C++/Java/Python language.

GRT Institute of Engineering and Technology, Tiruttani P a g e |7


| CS3401 Algorithms

Ex. No.: 1 LINEAR SEARCH

AIM:
To write a C program to 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.

ALGORITHM:

Step 1 : Declare the necessary variables including the array, the key element to be searched,
and the clock variables to measure the time taken.
Step 2 : Take the input values from the user, including the size of the array, the elements in
the array, and the key element to be searched.
Step 3 : Start the clock and perform the linear search on the given array to find the key
element.
Step 4 : Stop the clock and calculate the time taken to execute the search.
Step 5 : If the key element is found, display its position in the array. Otherwise, display a
message indicating that the search was unsuccessful.

PROGRAM:

linearsearch.c

// C program to perform Linear Search (Non-Recursive Code)

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

#define max 100


int pos;
int linsearch (int, int[], int);

void main()
{
double t;
int n, i, a[max], k, op, low, high;
clock_t begin, end;
clrscr();

printf("\nLinear Search \n");

printf("\n Enter the number of elements\n");


scanf("%d", &n);

printf("\n Enter the elements in any order \n");

GRT Institute of Engineering and Technology, Tiruttani P a g e |8


| CS3401 Algorithms

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


scanf("%d", &a[i]);

printf("\n Enter the element to be searched \n");


scanf("%d",&k);

begin = clock();
pos = linsearch(n, a, k);
end = clock();

if(pos == -1)
printf("\n\n Unsuccessful Search");
else
printf("Element %d is found at position %d", k, pos+1);
printf("\n Time taken is %lf CPU cycles \n",(end-begin)/CLK_TCK);

getch();
}

int linsearch(int n, int a[], int k)


{
int i;
delay(1000);

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


if(k == a[i])
break;

if(i>=n)
return -1;
else
return i;
}

GRT Institute of Engineering and Technology, Tiruttani P a g e |9


| CS3401 Algorithms

OUTPUT:

Linear Search
Enter the number of elements
5
Enter the elements in any order
12
4
23
54
24

Enter the element to be searched


24
Element 24 is found at position 5
Time taken is 0.989070 CPU cycles

No. of Time Taken


Elements (n) (cpu cycles)
5 0.989070
10 1.978022
20 2.783006
30 3.750240
40 1.978022
50 5.102127

RESULT:
Thus the C program for the implementation of Linear Search was done and
executed successfully. Also the graph for time taken versus n was plotted.

GRT Institute of Engineering and Technology, Tiruttani P a g e | 10


| CS3401 Algorithms

Ex. No.: 2 BINARY SEARCH

AIM:
To write a C program to 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.

ALGORITHM:

Step 1 : Declare the necessary variables including the array, the key element to be searched,
the low and high index values, and the clock variables to measure the time taken.
Step 2 : Take the input values from the user, including the size of the array, the elements in
the array (in ascending order), and the key element to be searched.
Step 3 : Start the clock and perform the binary search on the given array to find the key
element.
Step 4 : Stop the clock and calculate the time taken to execute the search. If the key element
is found, display its position in the array. Otherwise, display a message indicating
that the search was unsuccessful.

PROGRAM:

binarysearch.c

// C program to perform Binary Search using Recursion

#include<stdio.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>
#define max 100
int pos;
int binsearch (int,int[],int,int,int);
int linsearch (int,int[],int);
void main()
{
double t;
int n,i,a [max],k,op,low,high,pos;
clock_t begin,end;
clrscr();
printf("\nBinary Search \n");

printf("\n Enter the number of elements\n");


scanf("%d",&n);
printf("\n Enter the elements in ascending order \n");

for(i=0;i<n;i++)
scanf("%d",&a[i]);

GRT Institute of Engineering and Technology, Tiruttani P a g e | 11


| CS3401 Algorithms

printf("\n Enter the element to be searched \n");


scanf("%d",&k);

low = 0;
high = n-1;

begin = clock();
pos = binsearch(n,a,k,low,high);
end = clock();

if(pos == -1)
printf("\n\nUnsuccessful Search");
else
printf("\n Element %d is found at position %d", k, pos+1);

printf("\n Time Taken is %lf CPU cycles \n", (end-begin)/CLK_TCK);

getch();
}

int binsearch(int n,int a[],int k,int low,int high)


{
int mid;
delay(1000);
mid=(low+high)/2;

if(low > high)


return -1;
if(k == a[mid])
return(mid);
else if(k < a[mid])
return binsearch(n, a, k, low, mid-1);
else
return binsearch(n, a, k, mid+1, high);
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 12


| CS3401 Algorithms

OUTPUT:

Binary Search

Enter the number of elements


5

Enter the elements in ascending order


100
200
300
600
777

Enter the element to be searched


777

Element 777 is found at position 5


Time Taken is 11.978022 CPU cycles

No. of Time Taken


Elements (n) (cpu cycles)
5 11.978022
10 12.032967
20 13.956044
30 10.989070
40 13.021978
50 18.956044

RESULT:
Thus the C program for the implementation of Binary Search was done and
executed successfully. Also the graph for time taken versus n was plotted.

GRT Institute of Engineering and Technology, Tiruttani P a g e | 13


| CS3401 Algorithms

Ex. No.: 3 NAÏVE PATTERN MATCHING

AIM:
To write a C program to implement Naïve Pattern Matching - For the given text
txt[0...n-1] and the 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.

ALGORITHM:

Step 1: Initialize the text and pattern strings


Step 2: Implement the naive string matching algorithm
- Determine the lengths of the text and pattern strings
- Loop through the text string from index 0 to N-M
- For each index i, loop through the pattern string from index 0 to M-1
- If the character at index i+j in the text string does not match the character at index j
in the pattern string, break out of the inner loop
- If the inner loop completes without breaking, then the pattern has been found at
index i in the text string, so print out the index i
Step 3: Print out the text and pattern strings

PROGRAM:

// C program for Naive Pattern Searching algorithm

#include <stdio.h>
#include <string.h>

void search(char* pat, char* txt)


{
int i;
int M = strlen(pat);
int N = strlen(txt);

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


{
int j;

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


if (txt[i + j] != pat[j])
break;

if (j == M)
printf("Pattern found at index %d \n", i);
}
}

int main()
{
char txt[] = "AABAACAADAABAAABAA";

GRT Institute of Engineering and Technology, Tiruttani P a g e | 14


| CS3401 Algorithms

char pat[] = "AABA";

printf(“Naïve String Matching\n”);

printf("Text\n %s \n", txt);


printf("Pattern\n %s \n", pat);

search(pat, txt);

return 0;
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 15


| CS3401 Algorithms

OUTPUT:

Naive String Matching

Text
AABAACAADAABAAABAA

Pattern
AABA

Pattern found at index 0


Pattern found at index 9
Pattern found at index 13

--------------------------------
Process exited after 0.2837 seconds with return value 0
.

RESULT:
Thus the C program for the implementation of Naïve Pattern Matching was done
and executed successfully.

GRT Institute of Engineering and Technology, Tiruttani P a g e | 16


| CS3401 Algorithms

Ex. No.: 4a INSERTION SORT

AIM:
To write a C program to sort a given set of elements using the Insertion Sort and
determine the time 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.

ALGORITHM:

Step 1 : Start iterating from the second element of the array to the last element.
Step 2 : For the current element, store it in a temporary variable.
Step 3 : Compare the current element with the previous element and swap them if the
previous element is greater than the current element.
Step 4 : Repeat the previous step until the beginning of the array is reached or the previous
element is no longer greater than the current element.
Step 5 : Insert the current element at its correct position in the array.
Step 6 : Repeat steps 2-5 until the entire array is sorted.

PROGRAM:

insertionsort.c

// C program for Insertion Sort


#include<stdio.h>
#include<time.h>

void insertionsort(int a[], int n)


{
int i, j, temp;

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


{
temp = a[i];
j = i - 1;

while(j>=0 && temp <= a[j])


{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = temp;
}
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 17


| CS3401 Algorithms

void printArr(int a[], int n)


{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}

int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
clock_t begin,end;
int n = sizeof(a) / sizeof(a[0]);

printf("Before sorting array elements are - \n");


printArr(a, n);

begin = clock();
insertionsort(a, n);
end = clock();

printf("\nAfter sorting array elements are - \n");


printArr(a, n);

printf("\n Time Taken is %lf CPU cycles \n", (end-begin)/CLK_TCK);

return 0;
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 18


| CS3401 Algorithms

OUTPUT:

Before sorting array elements are -


12 31 25 8 32 17

After sorting array elements are -


8 12 17 25 31 32

Time Taken is 1.632550 CPU cycles

No. of Time Taken


Elements (n) (cpu cycles)
6 1.632550
10 4.402107
20 7.363102
30 12.537571
40 18.313609
50 16.317405

RESULT:
Thus the C program for the implementation of Insertion Sort was done and
executed successfully. Also the graph for time taken versus n was plotted.

GRT Institute of Engineering and Technology, Tiruttani P a g e | 19


| CS3401 Algorithms

Ex. No.: 4b HEAP SORT

AIM:
To write a C program to sort a given set of elements using the Heap Sort and
determine the time 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.

ALGORITHM:

Step 1: Read the number of elements (n) and the elements (arr[]) from the user
Step 2: Call the heapsort() function with n and arr[] as arguments
Step 3: In the heapsort() function, call the heapy() function with n and arr[] as arguments
Step 4: In the heapsort() function, for each element i from n to 1, swap the element at index 1
(root) with the element at index i, and then call the adjust() function with i-1 and arr[]
as arguments to restore the heap property
Step 5: In the heapy() function, for each element i from 1 to n, insert the element into the
heap by repeatedly swapping it with its parent until it is in the correct position

PROGRAM:
heapsort.c
// C program for Heap Sort

#include<stdio.h>
#include<conio.h>
#include<time.h>

void heapsort(int n, int arr[]);


void heapy(int n, int arr[]);
void adjust(int n, int arr[]);

void heapsort(int n, int arr[])


{
int i, item;
delay(100);
heapy(n, arr);
for(i=n; i>=1; i--)
{
item = arr[1];
arr[1] = arr[i];
arr[i] = item;
adjust(i, arr);
}
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 20


| CS3401 Algorithms

void heapy(int n, int arr[])


{
int i, j, k, item;

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


{
item = arr[i];
j = i;
k = j/2;

while(k != 0 && item > arr[k])


{
arr[j] = arr[k];
j = k;
k = j/2;
}

arr[j] = item;
}
}

void adjust(int n, int arr[])


{
int i, j, item;
j = 1;
item = arr[j];
i = j*2;

while(i<n)
{
if((i+1) < n)
{
if(arr[i] < arr[i+1])
i++;
}

if(item < arr[i])


{
arr[j] = arr[i];
j = i;
i = 2*j;
}
else
break;
}
arr[j] = item;
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 21


| CS3401 Algorithms

void main()
{
int i, n, arr[50];
clock_t end, start;
clrscr();

printf("\nEnter the number of Elements: \t");


scanf("%d",&n);
printf("\nEnter the %d Elements: \n",n);
for(i=1; i<=n; i++)
scanf("%d",&arr[i]);

start = clock();
heapsort(n, arr);
end = clock();

printf("\nSorted Elements are\n");


for(i=1; i<=n; i++)
printf("%d ",arr[i]);

printf("\nTime taken by Heapsort %lf CPU Cycles", (end-start)/CLK_TCK);


getch();
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 22


| CS3401 Algorithms

OUTPUT:

Enter the number of Elements: 5

Enter the 5 Elements:


20
12
45
23
100

Sorted Elements are


12 20 23 45 100
Time taken by Heapsort 14.780207 CPU Cycles

No. of Time Taken


Elements (n) (cpu cycles)
5 14.780207
10 17.741204
20 28.440987
30 41.894521
40 18.440058
50 76.461806

RESULT:
Thus the C program for the implementation of Heap Sort was done and executed
successfully. Also the graph for time taken versus n was plotted.

GRT Institute of Engineering and Technology, Tiruttani P a g e | 23


| CS3401 Algorithms

Ex. No.: 5 BREADTH FIRST SEARCH

AIM:
To write a C program to implement graph traversal using Breadth First Search.

ALGORITHM:

Step 1: Read the value of n and the adjacency matrix a[n][n] from the user
Step 2: Read the start node from the user, initialize the queue q[20], the visited array r[20],
and the start and end indices of the queue (st=0, ed=0)
Step 3: Enqueue the start node in the queue and mark it as visited in the visited array
Step 4: While the queue is not empty, repeat the following steps:
- Dequeue a node from the front of the queue
- For each adjacent node of the dequeued node that has not been visited yet, mark it as
visited, enqueue it in the queue, and print it as a reachable node from the start node
Step 5: If all nodes have been visited, print a message indicating that all nodes are reachable
from the start node. Otherwise, print a message indicating that not all nodes are
reachable from the start node.

PROGRAM:

// C program for graph traversal using Breadth First Search.

#include<stdio.h>
#include<conio.h>

void main()
{
int q[20], a[20][20], r[20], st=0, ed=0, start, n, i, j;
clrscr();
printf("\nEnter the value of n: ");
scanf("%d", &n);
printf("\nEnter the adjacency matrix: \n ");

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


{
for(j=0; j<n; j++)
{
scanf("%d", &a[i][j]);
r[i] = 0;
}
}
printf("\nEnter the start node: ");
scanf("%d", &start);
q[ed++] = start - 1;
r[start-1] = 1;
printf("\nNodes reachable from the origin(%d) are %d ",start, start);

GRT Institute of Engineering and Technology, Tiruttani P a g e | 24


| CS3401 Algorithms

while(st != ed)
{
for(i=0; i<n; i++)
{
if((r[i] == 0) && a[q[st]][i] == 1)
{
q[ed++]=i;
r[i]=1;
printf("%d ",i+1);
}
}
st++;
}

if(ed != n)
{
printf("\nAll nodes are not reachable from origin!!");
}
getch();
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 25


| CS3401 Algorithms

OUTPUT:

Enter the value of n: 5

Enter the adjacency matrix:


01101
10110
00111
11101
01110

Enter the start node: 1

Nodes reachable from the origin(1) are 1 2 3 5 4

RESULT:
Thus the C program for the implementation of graph traversal using Breadth First
Search was done and executed successfully.

GRT Institute of Engineering and Technology, Tiruttani P a g e | 26


| CS3401 Algorithms

Ex. No.: 6 DEPTH FIRST SEARCH

AIM:
To write a C program to implement graph traversal using Depth First Search.

ALGORITHM:

Step 1 : Define structure for node and graph.


Step 2 : Read number of vertices and number of edges.
Step 3 : Read edge details (vertex pair).
Step 4 : While the stack is not empty, check if there is an unvisited node adjacent to the top
of the stack. If so, mark it as visited and push it onto the stack.
Step 5 : If there are no unvisited adjacent nodes, pop the top node from the stack.
Step 6 : Print DFS order of vertices.

PROGRAM:

// C program for graph traversal using Depth First Search.

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

struct node
{
int vertexNumber;
struct node *pointerToNextVertex;
};

struct Graph
{
int numberOfVertices;
int *visitedRecord;
struct node **adjacencyLists;
};

struct node *createNodeForList(int v)


{
struct node *newNode = malloc(sizeof(struct node));
newNode->vertexNumber = v;
newNode->pointerToNextVertex = NULL;
return newNode;
}

void addEdgeToGraph(struct Graph *graph, int source, int destination)


{
struct node *newNode = createNodeForList(destination);
newNode->pointerToNextVertex = graph->adjacencyLists[source];

GRT Institute of Engineering and Technology, Tiruttani P a g e | 27


| CS3401 Algorithms

graph->adjacencyLists[source] = newNode;
newNode = createNodeForList(source);
newNode->pointerToNextVertex = graph->adjacencyLists[destination];
graph->adjacencyLists[destination] = newNode;
}

struct Graph *createGraph(int vertices)


{
int i;
struct Graph *graph = malloc(sizeof(struct Graph));
graph->numberOfVertices = vertices;
graph->adjacencyLists = malloc(vertices * sizeof(struct node *));
graph->visitedRecord = malloc(vertices * sizeof(int));

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


{
graph->adjacencyLists[i] = NULL;
graph->visitedRecord[i] = 0;
}

return graph;
}

void depthFirstSearch(struct Graph *graph, int vertexNumber)


{
struct node *adjList = graph->adjacencyLists[vertexNumber];
struct node *temp = adjList;
graph->visitedRecord[vertexNumber] = 1;
printf("%d ", vertexNumber);
while (temp != NULL)
{
int connectedVertex = temp->vertexNumber;
if (graph->visitedRecord[connectedVertex] == 0)
{
depthFirstSearch(graph, connectedVertex);
}
temp = temp->pointerToNextVertex;
}
}

int main()
{
int numberOfVertices, numberOfEdges, i;
int source, destination;
int startingVertex;

printf("Enter Number of Vertices and Edges in the Graph: ");


scanf("%d%d", &numberOfVertices, &numberOfEdges);
struct Graph *graph = createGraph(numberOfVertices);

GRT Institute of Engineering and Technology, Tiruttani P a g e | 28


| CS3401 Algorithms

printf("Add %d Edges of the Graph(Vertex numbering should be from 0 to %d)\n",


numberOfEdges, numberOfVertices - 1);
for (i = 0; i < numberOfEdges; i++)
{
scanf("%d%d", &source, &destination);
addEdgeToGraph(graph, source, destination);
}

printf("Enter Starting Vertex for DFS Traversal: ");


scanf("%d", &startingVertex);

if (startingVertex < numberOfVertices)


{
printf("DFS Traversal: ");
depthFirstSearch(graph, startingVertex);
}
return 0;
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 29


| CS3401 Algorithms

OUTPUT:

Enter Number of Vertices and Edges in the Graph: 6 7

Add 7 Edges of the Graph(Vertex numbering should be from 0 to 5)


01
12
02
23
43
53
54

Enter Starting Vertex for DFS Traversal: 2

DFS Traversal: 2 3 5 4 0 1

RESULT:
Thus the C program for the implementation of graph traversal using Depth First
Search was done and executed successfully.

GRT Institute of Engineering and Technology, Tiruttani P a g e | 30


| CS3401 Algorithms

Ex. No.: 7 DIJKSTRA’S ALGORITHM

AIM:
To develop a C program to find the shortest paths from a given vertex in a weighted
connected graph, to other vertices using Dijkstra’s algorithm.

ALGORITHM:

Step 1 : Define the macro INFINITY and the maximum size of the matrix as MAX.
Step 2 : Define the function dijkstra that takes the adjacency matrix, the number of vertices,
and the starting node as inputs.
Step 3 : Declare the variables cost, distance, pred, visited, count, mindistance, nextnode, i,
and j.
Step 4 : Initialize the cost matrix with the weights of the edges or infinity if there is no edge
between two nodes.
Step 5 : Initialize the distance, pred, and visited arrays with the information of the starting
node.
Step 6 : Use a loop to find the shortest path to all nodes by selecting the node with the
minimum distance from the starting node and updating the distance and pred arrays
accordingly.
Step 7 : Print the shortest distance and path from the starting node to all the other nodes in
the graph.

PROGRAM:

// C program for Dijkstra's algorithm.

#include<stdio.h>
#define INFINITY 9999
#define MAX 10

void dijkstra(int G[MAX][MAX],int n,int startnode);

int main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. of vertices: ");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");

for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
printf("\nEnter the starting node: ");
scanf("%d",&u);
dijkstra(G,n,u);
return 0;
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 31


| CS3401 Algorithms

void dijkstra(int G[MAX][MAX],int n,int startnode)


{
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;

for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];

for(i=0;i<n;i++)
{
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;

while(count<n-1)
{
mindistance=INFINITY;
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;
}
visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}

for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node %d = %d ",i,distance[i]);
printf("\nPath = %d ",i);
j=i;
do
{
j=pred[j];
printf(" <- %d ",j);
}while(j!=startnode);
}
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 32


| CS3401 Algorithms

OUTPUT:

Enter no. of vertices: 5

Enter the adjacency matrix:


0 10 0 30 100
10 0 50 0 0
0 50 0 20 10
30 0 20 0 60
100 0 10 60 0

Enter the starting node: 0

Distance of node 1 = 10
Path = 1 <- 0
Distance of node 2 = 50
Path = 2 <- 3 <- 0
Distance of node 3 = 30
Path = 3 <- 0
Distance of node 4 = 60
Path = 4 <- 2 <- 3 <- 0
..

RESULT:
Thus the C program for the implementation of Dijkstra’s algorithm was done and
executed successfully.

GRT Institute of Engineering and Technology, Tiruttani P a g e | 33


| CS3401 Algorithms

Ex. No.: 8 PRIM’S ALGORITHM

AIM:
To write a C program to find the minimum cost spanning tree of a given undirected
graph using Prim’s algorithm.

ALGORITHM:

Step 1 : Initialize the adjacency matrix 'G' and the spanning tree matrix 'spanning' with size
'MAX' and 'n'.
Step 2 : Read the number of vertices 'n' and the adjacency matrix 'G' from the user.
Step 3 : Initialize the 'distance', 'visited', 'from', and 'cost' arrays.
Step 4 : Set the 'distance' of the first vertex to 0 and mark it as 'visited'.
Step 5 : Traverse through all the vertices, find the minimum distance and mark it as 'visited'.
Step 6 : Update the 'distance' and 'from' arrays based on the minimum distance.
Step 7 : Continue the above process until all the edges are traversed and return the minimum
cost of the spanning tree.

PROGRAM:
// C program for Prim’s algorithm.
#include<stdio.h>
#include<stdlib.h>
#define infinity 9999
#define MAX 20
int G[MAX][MAX],spanning[MAX][MAX],n;
int prims();
int main()
{
int i,j,total_cost;
printf("Enter no. of vertices: ");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
total_cost=prims();
printf("\nSpanning Tree Matrix:\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",spanning[i][j]);
}
printf("\n\nTotal cost of minimum spanning tree = %d",total_cost);
return 0;
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 34


| CS3401 Algorithms

int prims()
{
int cost[MAX][MAX];
int u,v,min_distance,distance[MAX],from[MAX];
int visited[MAX],no_of_edges,i,min_cost,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(G[i][j]==0)
cost[i][j]=infinity;
else
cost[i][j]=G[i][j];
spanning[i][j]=0;
}
distance[0]=0;
visited[0]=1;
for(i=1;i<n;i++)
{
distance[i]=cost[0][i];
from[i]=0;
visited[i]=0;
}
min_cost=0;
no_of_edges=n-1;
while(no_of_edges>0)
{
min_distance=infinity;

for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distance)
{
v=i;
min_distance=distance[i];
}
u=from[v];
spanning[u][v]=distance[v];
spanning[v][u]=distance[v];
no_of_edges--;
visited[v]=1;
for(i=1;i<n;i++)
if(visited[i]==0&&cost[i][v]<distance[i])
{
distance[i]=cost[i][v];
from[i]=v;
}
min_cost=min_cost+cost[u][v];
}
return(min_cost);
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 35


| CS3401 Algorithms

OUTPUT:

Enter no. of vertices: 6

Enter the adjacency matrix:


021600
205030
150564
605002
036006
004260

Spanning Tree Matrix:

0 2 1 0 0 0
2 0 0 0 3 0
1 0 0 0 0 4
0 0 0 0 0 2
0 3 0 0 0 0
0 0 4 2 0 0

Total cost of minimum spanning tree = 12

RESULT:
Thus the C program for the implementation of Prim’s algorithm was done and
executed successfully.

GRT Institute of Engineering and Technology, Tiruttani P a g e | 36


| CS3401 Algorithms

Ex. No.: 9 FLOYD’S ALGORITHM

AIM:
To write a C program to implement Floyd’s algorithm for the All-Pairs-Shortest-Paths
problem.

ALGORITHM:

Step 1 : Define a function min() that takes two integers as input and returns the minimum of
the two.
Step 2 : Define a function floyds() that takes a 2D array of integers p and an integer n as
input. This function computes the shortest path between every pair of vertices in a
given weighted graph using Floyd's algorithm.
Step 3 : Inside the floyds() function, initialize the diagonal of the input matrix to 0 and
initialize all other elements to a very large value, e.g., 999.
Step 4 : Using a nested loop, iterate through all vertices and compute the shortest path
between them using the Floyd's algorithm.
Step 5 : Inside the main() function, read the number of vertices n and the number of edges e
of the graph from the user and initialize the input matrix p to 999 for all elements.
Step 6 : Read the end vertices and the weight of each edge from the user and update the
corresponding element in the input matrix p.
Step 7: Print the input matrix, the distance matrix obtained from floyds() function, and the
shortest paths between every pair of vertices.

PROGRAM:

// C program for Floyd’s algorithm.


#include<stdio.h>
int min(int,int);

void floyds(int p[10][10],int n)


{
int i,j,k;
for (k=1;k<=n;k++)
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
if(i==j)
p[i][j]=0;
else
p[i][j]=min(p[i][j],p[i][k]+p[k][j]);
}

int min(int a,int b)


{
if(a<b) return(a);
else return(b);
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 37


| CS3401 Algorithms

void main()
{
int p[10][10],w,n,e,u,v,i,j;
printf("\n Enter the number of vertices: ");
scanf("%d",&n);
printf("\n Enter the number of edges: ");
scanf("%d",&e);

for (i=1;i<=n;i++)
{
for (j=1;j<=n;j++)
p[i][j]=999;
}

for (i=1;i<=e;i++)
{
printf("\n Enter the end vertices of edge %d with its weight \n ",i);
scanf("%d%d%d",&u,&v,&w);
p[u][v]=w;
}

printf("\n Matrix of input data:\n");


for (i=1;i<=n;i++)
{
for (j=1;j<=n;j++)
printf("%d \t",p[i][j]);
printf("\n");
}

floyds(p,n);

printf("\n Distance Matrix:\n\n");


for (i=1;i<=n;i++)
{
for (j=1;j<=n;j++)
printf("%d \t",p[i][j]);
printf("\n");
}

printf("\n The shortest paths are:\n");


for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
{
if(i!=j)
printf("\n <%d,%d> = %d",i,j,p[i][j]);
}
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 38


| CS3401 Algorithms

OUTPUT:

Enter the number of vertices: 4


Enter the number of edges: 5
Enter the end vertices of edge 1 with its weight
133
Enter the end vertices of edge 2 with its weight
212
Enter the end vertices of edge 3 with its weight
327
Enter the end vertices of edge 4 with its weight
341
Enter the end vertices of edge 5 with its weight
416
Matrix of input data:
999 999 3 999
2 999 999 999
999 7 999 1
6 999 999 999

Distance Matrix:
0 10 3 4
2 0 5 6
7 7 0 1
6 16 9 0

The shortest paths are:


<1,2> = 10
<1,3> = 3
<1,4> = 4
<2,1> = 2
<2,3> = 5
<2,4> = 6
<3,1> = 7
<3,2> = 7
<3,4> = 1
<4,1> = 6
<4,2> = 16
<4,3> = 9
.

RESULT:
Thus the C program for the implementation of Floyd’s algorithm was done and
executed successfully.

GRT Institute of Engineering and Technology, Tiruttani P a g e | 39


| CS3401 Algorithms

Ex. No.: 10 WARSHALL'S ALGORITHM

AIM:
To write a C program to compute the transitive closure of a given directed graph
using Warshall's algorithm.

ALGORITHM:

Step 1 : Define a function Warshall’s that takes in the adjacency matrix p and the number of
vertices n as input.
Step 2 : Initialize variables i, j, and k to zero.
Step 3 : Use three nested loops, with k running from 1 to n, i running from 1 to n, and j
running from 1 to n.
Step 4 : Inside the innermost loop, update p[i][j] as follows:
p[i][j] = (p[i][j] || (p[i][k] && p[k][j])).
Step 5 : Define the main function, which takes in the number of vertices n and the number of
edges e as input.
Step 6 : Initialize the adjacency matrix p to zero for all elements using two nested for loops.
Step 7 : Inside a loop, take input for the end vertices of each edge and update the adjacency
matrix p accordingly. Finally, call the Warshall’s function passing the adjacency
matrix p and number of vertices n as arguments. Finally, print the transitive closure
of the graph.

PROGRAM:

// C program for Warshall's algorithm.

#include<stdio.h>

void warshalls(int p[10][10],int n)


{
int i,j,k;
for (k=1;k<=n;k++)
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
p[i][j]=(p[i][j] || (p[i][k] && p[k][j]));
}

void main()
{
int p[10][10],n,e,u,v,i,j;
printf("\n Enter the number of vertices: ");
scanf("%d",&n);
printf("\n Enter the number of edges: ");
scanf("%d",&e);

GRT Institute of Engineering and Technology, Tiruttani P a g e | 40


| CS3401 Algorithms

for (i=1;i<=n;i++)
{
for (j=1;j<=n;j++)
p[i][j]=0;
}

for (i=1;i<=e;i++)
{
printf("\n Enter the end vertices of edge %d \n ",i);
scanf("%d%d",&u,&v);
p[u][v]=1;
}
printf("\n Matrix of input data:\n");
for (i=1;i<=n;i++)
{
for (j=1;j<=n;j++)
printf("%d \t",p[i][j]);
printf("\n");
}

warshalls(p,n);

printf("\n Transitive Closure:\n\n");


for (i=1;i<=n;i++)
{
for (j=1;j<=n;j++)
printf("%d \t",p[i][j]);
printf("\n");
}

printf("\n The shortest paths are:\n");


for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
{
printf("\n <%d,%d> = %d",i,j,p[i][j]);
}
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 41


| CS3401 Algorithms

OUTPUT:

Enter the number of vertices: 4


Enter the number of edges: 4
Enter the end vertices of edge 1
12
Enter the end vertices of edge 2
24
Enter the end vertices of edge 3
41
Enter the end vertices of edge 4
43

Matrix of input data:


0 1 0 0
0 0 0 1
0 0 0 0
1 0 1 0

Transitive Closure:
1 1 1 1
1 1 1 1
0 0 0 0
1 1 1 1

The shortest paths are:


<1,1> = 1
<1,2> = 1
<1,3> = 1
<1,4> = 1
<2,1> = 1
<2,2> = 1
<2,3> = 1
<2,4> = 1
<3,1> = 0
<3,2> = 0
<3,3> = 0
<3,4> = 0
<4,1> = 1
<4,2> = 1
<4,3> = 1
<4,4> = 1

RESULT:
Thus the C program for the implementation of Warshall's algorithm was done and
executed successfully.

GRT Institute of Engineering and Technology, Tiruttani P a g e | 42


| CS3401 Algorithms

Ex. No.: 11 FINDING MIN AND MAX USING DIVIDE AND CONQUER

AIM:
To write a C program to find out the maximum and minimum numbers in a given list
of n numbers using the divide and conquer technique.

ALGORITHM:

Step 1 : Declare integer variables max, min and an integer array a of size 100
Step 2 : Define a function named maxmin which takes two integer parameters i and j
Step 3 : In the maxmin function, if i is equal to j, set max and min equal to a[i]
Step 4 : Otherwise, if i is equal to j-1, compare a[i] and a[j] to determine max and min
Step 5 : If i is neither equal to j nor j-1, recursively call the maxmin function by dividing the
array into two halves, calculate the max and min for each half, and then compare the
max and min of the two halves to determine the final max and min for the entire
array
Step 6 : In the main function, read the number of elements in the array from the user, read the
array elements from the user, call the maxmin function with appropriate arguments
and print the minimum and maximum values of the array.

PROGRAM:

// C program for finding Min and Max numbers in a given list.


#include<stdio.h>
#include<stdio.h>
int max, min;
int a[100];

void maxmin(int i, int j)


{
int max1, min1, mid;

if(i == j)
{
max = min = a[i];
}

else
{

if(i == j-1)
{
if(a[i] <a[j])
{
max = a[j];
min = a[i];
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 43


| CS3401 Algorithms

else
{
max = a[i];
min = a[j];
}
}

else
{
mid = (i+j) / 2;
maxmin(i, mid);
max1 = max; min1 = min;
maxmin(mid+1, j);

if(max < max1)


max = max1;

if(min > min1)


min = min1;
}
}
}

int main()
{
int i, num;
printf ("\nEnter the total number of numbers : ");
scanf ("%d", &num);
printf ("Enter the numbers : \n");

for (i=1; i<=num; i++)


scanf ("%d", &a[i]);

max = a[0];
min = a[0];
maxmin(1, num);
printf ("Minimum element in an array: %d\n", min);
printf ("Maximum element in an array: %d\n", max);
return 0;
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 44


| CS3401 Algorithms

OUTPUT:

Enter the total number of numbers : 15


Enter the numbers :
12345
4654758
454
8679
54675
8679675
454776
800
5654
157
2
3
46
6
654
Minimum element in an array: 2
Maximum element in an array: 8679675

RESULT:
Thus the C program for the implementation of finding min and max numbers in a
given list using divide and conquer technique was done and executed successfully.

GRT Institute of Engineering and Technology, Tiruttani P a g e | 45


| CS3401 Algorithms

Ex. No.: 12a MERGE SORT

AIM:
To write a C program to implement Merge sort method 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.

ALGORITHM
Step 1: Read number of elements n to sort
Step 2: Read n number of elements
Step 3: Calculate mid = (i + j) / 2
Step 4: merge_sort(i, mid, a, aux)
Step 5: merge_sort(mid + 1, j, a, aux)
Step 6: pointer_left = i, pointer_right = mid + 1
Step 7: for k in [i ... j]
if pointer_left points to smaller element,
aux[k] = a[pointer_left] and
increment pointer_left by 1
if pointer_right points to smaller element,
aux[k] = a[pointer_right] and
increment pointer_right by 1
copy the contents of aux[i .. j] to a[i .. j]
Step 8: Print sorted numbers

PROGRAM

// C program for Merge Sort

#include <stdio.h>
#include <time.h>

int merge_sort(int i, int j, int a[], int aux[])


{
if (j <= i)
{
return 0;
}

int mid = (i + j) / 2;

merge_sort(i, mid, a, aux);


merge_sort(mid + 1, j, a, aux);

int pointer_left = i;
int pointer_right = mid + 1;
int k;

GRT Institute of Engineering and Technology, Tiruttani P a g e | 46


| CS3401 Algorithms

for (k = i; k <= j; k++)


{
if (pointer_left == mid + 1)
{
aux[k] = a[pointer_right];
pointer_right++;
}
else if (pointer_right == j + 1)
{
aux[k] = a[pointer_left];
pointer_left++;
}
else if (a[pointer_left] < a[pointer_right])
{
aux[k] = a[pointer_left];
pointer_left++;
}
else
{
aux[k] = a[pointer_right];
pointer_right++;
}
}
for (k = i; k <= j; k++)
{
a[k] = aux[k];
}
}

int main()
{
int a[100], aux[100], n, i, d, swap;
clock_t begin, end;
printf("Enter number of elements in the array:\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);

begin = clock();
merge_sort(0, n - 1, a, aux);
end = clock();

printf("Printing the sorted array:\n");


for (i = 0; i < n; i++)
printf("%d\n", a[i]);

printf("\n Time Taken is %lf CPU cycles \n", (end-begin)/CLK_TCK);


return 0;
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 47


| CS3401 Algorithms

OUTPUT

Enter number of elements in the array:


10

Enter 10 integers
12
56
34
25
867
4
967
123
78
566

Printing the sorted array:


4
12
25
34
56
78
123
566
867
967

Time Taken is 33.219281 CPU cycles

No. of Time Taken


Elements (n) (cpu cycles)
10 33.219281
20 86.438562
30 147.206720
40 212.877120
50 282.192810

RESULT:
Thus the C program for the implementation of Merge Sort was done and executed
successfully. Also the graph for time taken versus n was plotted.

GRT Institute of Engineering and Technology, Tiruttani P a g e | 48


| CS3401 Algorithms

Ex. No.: 12b QUICK SORT

AIM:
To write a C program to implement Quick sort method 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.

ALGORITHM:

Step 1: Define a function quicksort() which accepts an array, the index of the first and last
element as arguments.
Step 2: If the first index is less than the last index, then select the first element as the pivot
element.
Step 3: Initialize two variables i and j to the first and last index respectively.
Step 4: Increment i until number[i] is greater than the pivot element, and decrement j until
number[j] is less than the pivot element.
Step 5: Swap the values of number[i] and number[j].
Step 6: Recursively call the quicksort() function for the two sub-arrays on both sides of the
pivot element.
Step 7: In the main function, accept input for the number of elements and the elements of the
array. Call the quicksort() function passing the array and the indices of the first and
last element. Print the sorted array and the time taken to execute the program.

PROGRAM:

// C program for Quick Sort

#include<stdio.h>
#include <time.h>

void quicksort(int number[50],int first,int last)


{
int i, j, pivot, temp;

if(first < last)


{
pivot=first;
i=first;
j=last;

while(i<j)
{

while(number[i]<=number[pivot] && i<last)


i++;
while(number[j] > number[pivot])
j--;

GRT Institute of Engineering and Technology, Tiruttani P a g e | 49


| CS3401 Algorithms

if(i < j)
{
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;

quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}

int main()
{
int i, n, number[50];
clock_t begin, end;

printf("Enter value of n: ");


scanf("%d",&n);

printf("Enter %d elements: \n", n);

for(i=0;i<n;i++)
scanf("%d",&number[i]);

begin = clock();

quicksort(number,0,n-1);

end = clock();

printf("The Sorted Order is: \n");

for(i=0;i<n;i++)
printf(" %d",number[i]);

printf("\n Time Taken is %lf CPU cycles \n", (end-begin)/CLK_TCK);


return 0;
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 50


| CS3401 Algorithms

OUTPUT:

Enter value of n: 10

Enter 10 elements:
76
45
78
98
45
23
686
5454
5
21

The Sorted Order is:


5 21 23 45 45 76 78 98 686 5454

Time Taken is 26.273600 CPU cycles

No. of Time Taken


Elements (n) (cpu cycles)
10 26.273600
15 58.603359
20 86.438562
25 116.096400
30 147.206720

RESULT:
Thus the C program for the implementation of Quick Sort was done and executed
successfully. Also the graph for time taken versus n was plotted.

GRT Institute of Engineering and Technology, Tiruttani P a g e | 51


| CS3401 Algorithms

Ex. No.: 13 N-QUEENS PROBLEM USING BACKTRACKING

AIM:
To write a C program to implement N-Queens problem using Backtracking.

ALGORITHM:

Step 1: Declare global variables: board[20], count.


Step 2: Define a function to print the solution.
Step 3: Define a function to check if it is safe to place the queen at a given row and column.
Step 4: Define a recursive function queen() to place the queens on the board.
Step 5: In the queen() function, check if a queen can be placed in a column of the current
row.
Step 6: If a queen can be placed, place it and recursively call the queen() function to place
the queens in the next rows.
Step 7: If all queens are placed on the board, print the solution. If no solution is found,
backtrack to the previous row and try another column.

PROGRAM:

// C program for N-Queens problem using Backtracking.

#include<stdio.h>
#include<math.h>

int board[20],count;

int main()
{
int n,i,j;
void queen(int row,int n);

printf("N-Queens Problem Using Backtracking");


printf("\n\nEnter number of Queens: ");
scanf("%d",&n);
queen(1,n);
return 0;
}

void print(int n)
{
int i,j;
printf("\n\nSolution %d:\n\n",++count);

for(i=1;i<=n;++i)
printf("\t%d",i);

GRT Institute of Engineering and Technology, Tiruttani P a g e | 52


| CS3401 Algorithms

for(i=1;i<=n;++i)
{
printf("\n\n%d",i);
for(j=1;j<=n;++j)
{
if(board[i]==j)
printf("\tQ");
else
printf("\t-");
}
}
}

int place(int row,int column)


{
int i;
for(i=1;i<=row-1;++i)
{
if(board[i]==column)
return 0;
else
if(abs(board[i]-column)==abs(i-row))
return 0;
}

return 1;
}

void queen(int row,int n)


{
int column;
for(column=1;column<=n;++column)
{
if(place(row,column))
{
board[row]=column;
if(row==n)
print(n);
else
queen(row+1,n);
}
}
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 53


| CS3401 Algorithms

OUTPUT:

N-Queens Problem Using Backtracking

Enter number of Queens: 4

Solution 1:

1 2 3 4

1 - Q - -

2 - - - Q

3 Q - - -

4 - - Q -

Solution 2:

1 2 3 4

1 - - Q -

2 Q - - -

3 - - - Q

4 - Q - -

RESULT:
Thus the C program for the implementation of N-Queens problem using
Backtracking was done and executed successfully.

GRT Institute of Engineering and Technology, Tiruttani P a g e | 54


| CS3401 Algorithms

Ex. No.: 14 TRAVELING SALESPERSON PROBLEM

AIM:
To write a C program to 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.

ALGORITHM:

Step 1 : Declare and initialize the necessary variables and arrays.


Step 2 : Take input from the user for the number of villages and the cost matrix.
Step 3 : Initialize the completed array to 0.
Step 4 : Find the minimum cost path using the mincost function by recursively calling least
function.
Step 5 : The least function returns the nearest unvisited city.
Step 6 : If all the cities are visited, return back to the starting city and print the minimum
cost.
Step 7 : Print the path and minimum cost.

PROGRAM:

// C program for Traveling Salesperson Problem.


tsp.c
#include<stdio.h>
int ary[10][10], completed[10], n, cost = 0;

void takeInput()
{
int i,j;

printf("Enter the number of villages: ");


scanf("%d", &n);

printf("\nEnter the Cost Matrix\n");

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


{
printf("\nEnter Elements of Row: %d\n", i+1);

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


scanf("%d", &ary[i][j]);

completed[i] = 0;
}
printf("\n\nThe cost list is: ");

GRT Institute of Engineering and Technology, Tiruttani P a g e | 55


| CS3401 Algorithms

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


{
printf("\n");

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


printf("\t%d", ary[i][j]);
}
}

void mincost(int city)


{
int i, ncity;
completed[city] = 1;
printf("%d--->", city+1);
ncity = least(city);

if(ncity == 999)
{
ncity = 0;
printf("%d", ncity+1);
cost += ary[city][ncity];

return;
}

mincost(ncity);
}

int least(int c)
{
int i, nc = 999;
int min = 999, kmin;

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


{
if((ary[c][i] != 0) && (completed[i] == 0))
if(ary[c][i] + ary[i][c] < min)
{
min = ary[i][0] + ary[c][i];
kmin = ary[c][i];
nc = i;
}
}

if(min != 999)
cost += kmin;

return nc;
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 56


| CS3401 Algorithms

int main()
{
takeInput();

printf("\n\nThe Path is: \n");


mincost(0);

printf("\n\nMinimum cost is %d\n ", cost);

return 0;
}

// Traveling Salesperson Problem using Approximation Algorithm.

tspapprox.c

#include<stdio.h>
int c = 0,cost = 999;

int graph[4][4] = { {0, 4, 1, 3},


{4, 0, 2, 1},
{1, 2, 0, 5},
{3, 1, 5, 0}
};

void swap (int *x, int *y)


{
int temp;
temp = *x;
*x = *y;
*y = temp;
}

void copy_array(int *a, int n)


{
int i, sum = 0;
for(i = 0; i <= n; i++)
{
sum += graph[a[i % 4]][a[(i + 1) % 4]];
}
if (cost > sum)
{
cost = sum;
}
}
void permute(int *a, int i, int n)
{
int j, k;

GRT Institute of Engineering and Technology, Tiruttani P a g e | 57


| CS3401 Algorithms

if (i == n)
{
copy_array(a, n);
}
else
{
for (j = i; j <= n; j++)
{
swap((a + i), (a + j));
permute(a, i + 1, n);
swap((a + i), (a + j));
}
}
}

int main()
{
int i, j;
int a[] = {0, 1, 2, 3};
permute(a, 0, 3);
printf("minimum cost: %d",cost);

GRT Institute of Engineering and Technology, Tiruttani P a g e | 58


| CS3401 Algorithms

OUTPUT:

Output of tsp.c

Enter the number of villages: 4


Enter the Cost Matrix
Enter Elements of Row: 1
0413
Enter Elements of Row: 2
4021
Enter Elements of Row: 3
1205
Enter Elements of Row: 4
3150
The cost list is:
0413
4021
1205
3150
The Path is:
1—>3—>2—>4—>1
Minimum cost is 7

Output of tspaprox.c

minimum cost: 7

Error:

Error in Approximation = 0

RESULT:
Thus the C program for the implementation of Traveling Salesperson Problem
was done and executed successfully.

GRT Institute of Engineering and Technology, Tiruttani P a g e | 59


| CS3401 Algorithms

Ex. No.: 15 FINDING THE KTH SMALLEST NUMBER

AIM:
To write a C program to implement randomized algorithm for finding the kth smallest
number.

ALGORITHM:

Step 1 : Initialize an array A of size N and fill it with random values.


Step 2 : Read an integer K from the user, representing the Kth smallest element to be found
in the array.
Step 3 : Define a function swap that swaps two elements in an array.
Step 4 : Define a function partition that takes two indices (start and end) and partitions the
array based on a pivot element selected at the start index. This function also uses the
swap function.
Step 5 : Define a function quick_sort that takes three arguments (start, end, and K). This
function first partitions the array using the partition function, and then recursively
calls itself on the sub-arrays to the left or right of the partition depending on the
value of K and the position of the partition.
Step 6 : In the main function, call the quick_sort function with arguments 0 (start index),
N(end index), and K.
Step 7 : When the partition index equals K - 1, print the Kth smallest element and return
from the quick_sort function.

PROGRAM:

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

int N = 20;
int A[20];

void swap(int dex1, int dex2)


{
int temp = A[dex1];
A[dex1] = A[dex2];
A[dex2] = temp;
}

int partition(int start, int end)


{
int i = start + 1;
int j = i;
int pivot = start;

GRT Institute of Engineering and Technology, Tiruttani P a g e | 60


| CS3401 Algorithms

for (; i < end; i++)


{
if (A[i] < A[pivot])
{
swap(i, j);
j++;
}
}
if (j <= end)
swap(pivot, (j - 1));

return j - 1;
}

void quick_sort(int start, int end, int K)


{
int part;
if (start < end)
{
part = partition(start, end);
if (part == K - 1)
printf("kth smallest element : %d ", A[part]);
if (part > K - 1)
quick_sort(start, part, K);
else
quick_sort(part + 1, end, K);
}
return;
}

int main(int argc, char **argv)


{
int i;
int k;
time_t seconds;
time(&seconds);
srand((unsigned int) seconds);

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


A[i] = rand() % (1000 - 1 + 1) + 1;

printf("The original sequence is: ");


for (i = 0; i < N; i++)
printf("%d ", A[i]);

printf("\nEnter the Kth smallest you want to find: ");

scanf("%d", &k);
quick_sort(0, N, k);
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 61


| CS3401 Algorithms

OUTPUT:

The original sequence is:


289 16 207 633 774 928 783 360 911 526 171 508 966 18 250 238 453 801 420 802

Enter the Kth smallest you want to find: 5

kth smallest element : 238

RESULT:
Thus the C program for the implementation of randomized algorithm for finding
th
the k smallest number was done and executed successfully.

GRT Institute of Engineering and Technology, Tiruttani P a g e | 62


| CS3401 Algorithms

CONTENT BEYOND SYLLABUS

GRT Institute of Engineering and Technology, Tiruttani P a g e | 63


| CS3401 Algorithms

Ex. No.: 16 FINDING CYCLE IN A DIRECTED GRAPH

AIM:
To write a C program to find whether a Directed Graph is Cyclic or not.

ALGORITHM:

Step 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a stack.
Step 2 − If no adjacent vertex is found, pop up a vertex from the stack.
(It will pop up all the vertices from the stack, which do not have adjacent vertices.)
Step 3 − Repeat Step 1 and Step 2 until the stack is empty.

PROGRAM:

/* C Program to find whether a Directed Graph is Cyclic or not */


#include<stdio.h>
#include<stdlib.h>
#define MAX 100
#define initial 1
#define visited 2
#define finished 3
int n; /*Number of vertices in the graph */
int adj[MAX][MAX];
void create_graph( );
int state[MAX];
void DF_Traversal();
void DFS(int v);
int main()
{
create_graph();
DF_Traversal();
return 0;
}/*End of main()*/

void DF_Traversal()
{
int v;
for(v=0; v<n; v++)
state[v] = initial;
DFS(0);/*start DFS from vertex 0*/
for(v=0; v<n; v++)
{
if(state[v]==initial)
DFS(v);
}
printf("\nGraph is Acyclic\n");
}/*End of DF_Traversal( )*/

GRT Institute of Engineering and Technology, Tiruttani P a g e | 64


| CS3401 Algorithms

void DFS(int v)
{
int i;
state[v] = visited;

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


{
if(adj[v][i]==1)
{
if(state[i]==initial)
DFS(i);
else if(state[i]==visited)
{
printf("\nBack edge (%d,%d) found\n", v, i);
printf("\nGraph is cyclic\n");
exit(1);
}
}
}
state[v] = finished;
}/*End of DFS()*/

void create_graph()
{
int i,max_edges,origin,destin;

printf("\nEnter number of vertices : ");


scanf("%d",&n);
max_edges = n*(n-1);
for(i=1;i<=max_edges;i++)
{
printf("\nEnter edge %d (-1 -1 to quit ) : ",i);
scanf("%d %d",&origin,&destin);
if( (origin == -1) && (destin == -1) )
break;
if( origin >= n || destin >= n || origin<0 || destin<0)
{
printf("\nInvalid edge!\n");
i--;
}
else
{
adj[origin][destin] = 1;
}
}
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 65


| CS3401 Algorithms

OUTPUT:

Enter number of vertices: 6

Enter edge 1(-1 -1 to quit ) : 0 1

Enter edge 2(-1 -1 to quit ) : 0 2

Enter edge 3(-1 -1 to quit ) : 0 3

Enter edge 4(-1 -1 to quit ) : 1 3

Enter edge 5(-1 -1 to quit ) : 3 4

Enter edge 6(-1 -1 to quit ) : 2 5

Enter edge 7(-1 -1 to quit ) : 5 4

Enter edge 8(-1 -1 to quit ) : -1 -1

Graph is Acyclic

RESULT:
Thus the C program for the implementation of finding cycle in a directed graph
was done and executed successfully.

GRT Institute of Engineering and Technology, Tiruttani P a g e | 66


| CS3401 Algorithms

Ex. No.: 17 JOB ASSIGNMENT PROBLEM USING BRANCH AND BOUND

AIM:
To write a C++ program to implement Job Assignment Problem using Branch and
Bound technique.

ALGORITHM:

// Input: Cost Matrix of Job Assignment problem

// Output: Optimal cost and Assignment of Jobs

algorithm findMinCost (costMatrix mat[][])


{
// Initialize list of live nodes(min-Heap)
// with root of search tree i.e. a Dummy node

while (true)
{
// Find a live node with least estimated cost
E = Least();

// The found node is deleted from the list


// of live nodes

if (E is a leaf node)
{
printSolution();
return;
}

for each child x of E


{
Add(x); // Add x to list of live nodes;
x->parent = E; // Pointer for path to root
}
}
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 67


| CS3401 Algorithms

PROGRAM:

// Program to solve Job Assignment problem using Branch and Bound

#include <bits/stdc++.h>

using namespace std;

#define N 4

// state space tree node


struct Node
{
Node* parent;
int pathCost;
int cost;
int workerID;
int jobID;
bool assigned[N];
};

Node* newNode(int x, int y, bool assigned[], Node* parent)


{
Node* node = new Node;

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


node->assigned[j] = assigned[j];

node->assigned[y] = true;

node->parent = parent;
node->workerID = x;
node->jobID = y;

return node;
}

int calculateCost(int costMatrix[N][N], int x, int y, bool assigned[])


{
int cost = 0;
bool available[N] = {true};

for (int i = x + 1; i < N; i++)


{
int min = INT_MAX, minIndex = -1;

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


{
if (!assigned[j] && available[j] && costMatrix[i][j] < min)
{

GRT Institute of Engineering and Technology, Tiruttani P a g e | 68


| CS3401 Algorithms

minIndex = j;
min = costMatrix[i][j];
}
}
cost += min;
available[minIndex] = false;
}
return cost;
}

struct comp
{
bool operator()(const Node* lhs, const Node* rhs) const
{
return lhs->cost > rhs->cost;
}
};

void printAssignments(Node *min)


{
if(min->parent==NULL)
return;

printAssignments(min->parent);
cout << "Assign Worker " << char(min->workerID + 'A')
<< " to Job " << min->jobID << endl;
}

// Finds minimum cost using Branch and Bound.


int findMinCost(int costMatrix[N][N])
{
priority_queue<Node*, std::vector<Node*>, comp> pq;
bool assigned[N] = {false};
Node* root = newNode(-1, -1, assigned, NULL);
root->pathCost = root->cost = 0;
root->workerID = -1;
pq.push(root);

while (!pq.empty())
{
Node* min = pq.top();
pq.pop();
int i = min->workerID + 1;

if (i == N)
{
printAssignments(min);
return min->cost;
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 69


| CS3401 Algorithms

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


{
if (!min->assigned[j])
{
Node* child = newNode(i, j, min->assigned, min);
child->pathCost = min->pathCost + costMatrix[i][j];

child->cost = child->pathCost +
calculateCost(costMatrix, i, j, child->assigned);

pq.push(child);
}
}
}
}

// Driver code
int main()
{
// x-coordinate represents a Worker
// y-coordinate represents a Job
int costMatrix[N][N] =
{
{9, 2, 7, 8},
{6, 4, 3, 7},
{5, 8, 1, 8},
{7, 6, 9, 4}
};

cout << "\nOptimal Cost is " << findMinCost(costMatrix);

return 0;
}

GRT Institute of Engineering and Technology, Tiruttani P a g e | 70


| CS3401 Algorithms

OUTPUT:

Assign Worker A to Job 1


Assign Worker B to Job 0
Assign Worker C to Job 2
Assign Worker D to Job 3

Optimal Cost is 13

RESULT:
Thus the C++ program for the implementation of Job Assignment Problem using
Branch and Bound technique was done and executed successfully.

GRT Institute of Engineering and Technology, Tiruttani P a g e | 71

You might also like