0% found this document useful (0 votes)
114 views23 pages

Design and Analysis of Algorithms

It contains proper conceptual programming and designing of the iterative algorithms, divide and conquer algorithms, backtracking algorithms and dynamic programming.

Uploaded by

gopelaw218
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
114 views23 pages

Design and Analysis of Algorithms

It contains proper conceptual programming and designing of the iterative algorithms, divide and conquer algorithms, backtracking algorithms and dynamic programming.

Uploaded by

gopelaw218
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 23

LAB 1: Iterative Algorithm

EXPERIMENT 1: TO DESIGN AND IMPLEMENT ITERATIVE SORTING


ALGORITHM

1. OBJECTIVE:
• To design and implement insertion sort algorithm.
• To design and implement selection sort algorithm.
• To design and implement bubble sort and algorithm.

2. THEORY:
Insertion Sort:
It is a comparison based sorting algorithm. where, a sub-list is maintained which is always
sorted. The lower part of an array is maintained to be sorted. The element which is to be
inserted in the sorted sub-list, has to find its appropriate place and insert it there. Hence
the name insertion sort. The array is searched sequentially and unsorted items are moved
and inserted into sorted sub-list in the same array. This algorithm is not suitable for large
data sets as its average and worst case complexity are of Ο(n2),where n is no. of items.

Algorithm:
1. If it is the first element, it is already sorted. return 1;
2. Pick next element
3. Compare with all elements in the sorted sub-list
4. Find appropriate position
5. Insert the value
6. Repeat until list is sorted

Selection Sort:
It is a comparison based algorithm in which the list is divided into two parts, sorted part
at left end and unsorted part at right end. Initially sorted part is empty and unsorted part is
entire list. Smallest element is selected from the unsorted array and swapped with the
leftmost element and that element becomes part of sorted array. This process continues
moving unsorted array boundary by one element to the right. This algorithm is not suitable
for large data sets as its average and worst case complexity are of O(n2) where n is no. of
items.

Algorithm:
1. Set MIN to location 0
2. Search the minimum element in the list
3. Swap with value at location MIN
4. Increment MIN to point to next element
5. Repeat until list is sorted
Bubble Sort:
Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them
until they are in the intended order.Just like the movement of air bubbles in the water that
rise up to the surface, each element of the array move to the end in each iteration.
Therefore, it is called a bubble sort. It performs equally for all array so the running time
complexity is O(n2)

Algorithm:
1. Starting from the first index, compare the first and the second elements.
2. If the first element is greater than the second element, they are swapped.
3. Now, compare the second and the third elements. Swap them if they are not in order.
4. The above process goes on until the last element.

3. IMPLEMENTATION:
PROGRAM 1: Program for insertion sort algorithm
Source code:
#include <stdio.h>
#include <stdlib.h>
void insertionSort(int a[ ], int n)
{
int i, j, key;
for (j = 1; j < n; j++)
{
key = a[j];
i = j - 1;
while (i >= 0 && key < a[i])
{
a[i + 1] = a[i];
i--;
}
a[i + 1] = key;
}
}

int main()
{
int i, a[100], n;
printf("\n Enter the size of the array: ");
scanf("%d", &n);
printf("\n Enter the elements of the array: \n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("\nBefore Sorting: ");
for (i = 0; i < n; i++)
printf("%d\t", a[i]);
insertionSort(a, n);
printf("\nAfter Sorting: ");
for (i = 0; i < n; i++)
printf("%d\t", a[i]);
return 0;
}

Output:

PROGRAM 2: Program for Selection sort algorithm


Source code:
#include <stdio.h>
void SelectSort(int a[], int n);
int main()
{
int a[100], n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter the elements of array: \n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
SelectSort(a, n);
return 0;
}

void SelectSort(int a[], int n)


{
int i, j, position, swap;
for (i = 0; i < (n - 1); i++)
{
position = i;
for (j = i + 1; j < n; j++)
{
if (a[position] > a[j])
position = j;
}
if (position != i)
{
swap = a[i];
a[i] = a[position];
a[position] = swap;
}
}
printf("Sorted Array:\t");
for (i = 0; i < n; i++)
printf("%d\t", a[i]);
}
Output:

PROGRAM 3: Program to implement Bubble Sort algorithm.


Source code:
#include <stdio.h>
void bubbleSort(int array[], int size)
{
for (int step = 0; step < size - 1; ++step)
{
for (int i = 0; i < size - step - 1; ++i) {
if (array[i] > array[i + 1]) {
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
}
int main()
{
int i,size;
printf("Enter the total number of elements: ");
scanf("%d",&size);
int data[size];
printf("Enter the element of array: \n");
for(i=0;i<size;i++)
{
scanf("%d",&data[i]);
}
bubbleSort(data, size);
printf("Sorted Array: ");
for(i=0;i<size;i++){
printf(" %d\t",data[i]);
}
}
Output:

4. RESULT & DISCUSSION:


Program1 was implementation of insertion sort where array of size 8 with unsorted
element was input and it successfully sorted the array in ascending form.

Program 2 was implementation of selection sort where array of size 8 with unsorted
element was input and it successfully sorted the array in ascending form.

Program 3 was implementation of Bubble sort where array of size 7 with unsorted
element was input and it successfully sorted the array in ascending form

5. CONCLUSION:
Hence, three iterative sorting algorithm selection sort insertion sort and bubble sort
was successfully created and implemented using c program
LAB 1: Iterative Algorithm

EXPERIMENT 2: TO IMPLEMENT EUCLIDEAN ALGORITHM TO FIND


GCD OF TWO INTEGERS.

1. OBJECTIVE:
• To implement Euclidean algorithm.
• To find the GCD of two integer.

2. THEORY:
Euclidean Algorithm:
The Euclidean algorithm is a way to find the greatest common divisor of two positive
integers. GCD of two numbers is the largest number that divides both of them. A simple
way to find GCD is to factorize both numbers and multiply common prime factors.
Time Complexity: O(Log min(a, b))
Extended Euclidean Algorithm:
Extended Euclidean algorithm also finds integer coefficients x and y such that:
ax + by = gcd(a, b)
The extended Euclidean algorithm updates the results of gcd(a, b) using the results
calculated by the recursive call gcd(b%a, a). Let values of x and y calculated by the
recursive call be x1 and y1. x and y are updated using the below expressions.
ax + by = gcd(a, b)
gcd(a, b) = gcd(b % a, a)
gcd(b % a, a) = (b % a)x1 + ay1
ax + by = (b % a) x1 + ay1
ax + by = (b – [b/a] * a) x1 + ay1
ax + by = a (y1 – [b/a] * x1) + bx1
Comparing LHS and RHS,
x = y1 – ⌊b/a⌋ * x1
y = x1

3. IMPLEMENTATION:
PROGRAM :
Source code:
#include <stdio.h>
int gcdExtended(int a, int b, int *x, int *y)
{
if (a == 0)
{
*x = 0;
*y = 1;
return b;
}
int x1, y1;
int gcd = gcdExtended(b%a, a, &x1, &y1);
*x = y1 - (b/a) * x1;
*y = x1;

return gcd;
}
int main()
{
int x, y, b ,a;
printf("\nEnter the numbers a & b: \n");
scanf("%d%d",&a,&b);
int g = gcdExtended(a, b, &x, &y);
printf("gcd(%d, %d) = %d", a, b, g);
return 0;
}
Output:

4. RESULT & DISCUSSION:


In Above extended Euclidean algorithm gcd between 2 integer 35 and 15 was calculated and
result was 5 which is correct

5. CONCLUSION:
Hence , extended Euclidean algorithm was successfully implemented using c program
LAB 2: Divide and Conquer

EXPERIMENT 1: TO DESIGN AND IMPLEMENT MERGE SORT AND


QUICK SORT ALGORITHM.

1. OBJECTIVE:
• To implement the merge sort algorithm.
• To implement the quick sort algorithm.

2. THEORY:
Merge Sort:
The merge sort is an efficient sorting algorithm which is based on divide and conquer
approach. An array of size is divided recursively until the size of each sub-list is equal to
1. After the complete division process the algorithm merge two adjacent list into single
list recursively. Merging is combining two sorted list.
Complexity of this algorithm is T(n) = O(nlogn)

Algorithm:
1. if it is only one element in the list it is already sorted, return.
2. divide the list recursively into two halves until it can no more be divided.
3. merge the smaller lists into new list in sorted order.

Quick Sort:
The quick sorting algorithm is also based on divide and conquer algorithm.it is also
called a part ion exchange sorting .The central concept of these algorithm is partitioning
the array about an element called pivot element. An array A[ ] is said to be partitioned
about an item A[i]. if all the elements to the left of A[i] are less or equal to A[i] and all
items to the right of A[i] are greater than A[i]

Algotithm:
1. Pick an element from an array, call it as pivot element.
2. Divide an unsorted array element into two arrays.
3. If the value less than pivot element come under first sub array, the remaining elements
with value greater than pivot come in second sub array.

3. IMPLEMENTATION:
PROGRAM 1: program to implement merge sort.
Source code:
#include <stdio.h>
void merge(int arr[ ], int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

int L[n1], R[n2];


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; 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 mergeSort(int arr[], int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;

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

merge(arr, l, m, r);}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");}

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int arr_size = sizeof(arr) / sizeof(arr[0]);

printf("Unsorted array: \n");


printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);

printf("Sorted array: \n");


printArray(arr, arr_size);

return 0;
}
Output:

PROGRAM 2: program to implement quick sort.


Source code:
#include<stdio.h>
void quicksort(int number[25],int first,int last){
int j;
if(first<last){
j=partition(number,first,last);
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}
int partition(int number[],int i,int j){
int l, r, pivot, temp;
pivot=i;
l=i;
r=j;
while(l<r){
while(number[l]<=number[pivot]&&l<=j){
l++;
}
while(number[r]>number[pivot]){
r--;
}

if(l<r){
temp=number[l];
number[l]=number[r];
number[r]=temp;
}
}
temp=number[pivot];
number[pivot]=number[r];
number[r]=temp;
return r;
}
int main(){
int i, count, number[25];
printf("Enter the total number of elements: ");
scanf("%d",&count);
printf("Enter the element of array: \n");
for(i=0;i<count;i++)
{
scanf("%d",&number[i]);
}
quicksort(number,0,count-1);
printf("Sorted array: ");
for(i=0;i<count;i++){
printf(" %d\t",number[i]);
}

return 0;
}

Output:

4. RESULT & DISCUSSION:


Program1 was implementation of merge sort where array of size 9 with unsorted
element was input and it successfully sorted the array in ascending form.
Program 2 was implementation of quick sort where array of size 9 with unsorted
element was input and it successfully sorted the array in ascending form.

5. CONCLUSION:
Hence, two divide and conquer sorting algorithm merge sort and quick sort was
successfully created and implemented using c program
LAB 2: Divide and Conquer

EXPERIMENT 2: TO DESIGN AND IMPLEMENT HEAP SORT


ALGORITHM.

1. OBJECTIVE:
• To study the heap sort algorithm.
• To implement the heap sort algorithm in c program

2. THEORY:
Heap Sort:
Heap Sort is a popular and efficient sorting algorithm in computer programming. The
initial set of numbers are stored in an array Heap sort works by visualizing the elements
of the array as a special kind of complete binary tree called a heap.
Heap
Heap is a special tree-based data structure. A binary tree is said to follow a heap data
structure if
• it is a complete binary tree
• All nodes in the tree follow the property that they are greater than their children
i.e. the largest element is at the root and both its children are smaller than the root
and so on. Such a heap is called a max-heap. If instead, all nodes are smaller than
their children, it is called a min-heap
Heapify:
In order to maintain the max heap property we call the procedure maxHeapify. It's input
an array A and index i i.e, A[i], when maxheapify is called it assumes that left & right
are max heaps but A[i] might be smaller than its children. Thus violating violating the
max heap property. max heapity lets the value at A[i] float down. in the max heap so
that the subtree rooted at index i obeys. the maxheap property.

Build maxheap:
To build a max-heap from any tree, we can thus start heapifying each sub-tree
from the bottom up and end up with a max-heap after the function is applied to all the
elements including the root element.In the case of a complete tree, the first index of a
non-leaf node is given by n/2 - 1. All other nodes after that are leaf-nodes and thus don't
need to be heapified.

Algorithm:
1. Build a max heap of the array a[n]
2. For(j=n down to 1
a.Exchange jth position element with root
b.Perform the maxheapify by reducing the heapsize by 1
3. Reheapify the remaining elements into a heap size by calling heapify on root node.
4. Call Recursively. Repeat steps 2 and 3 as long as heap size is greater than 2.
3. IMPLEMENTATION:
PROGRAM 1:
Source code:
#include <stdio.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

void heapify(int arr[ ], int n, int i)


{
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && arr[left] > arr[largest])


largest = left;

if (right < n && arr[right] > arr[largest])


largest = right;

if (largest != i)
{
swap(&arr[i], &arr[largest]);
heapify(arr, n, largest);
}
}

void heapSort(int arr[ ], int n)


{

for (int i = n / 2 - 1; i >= 0; i--)


heapify(arr, n, i);

for (int i = n - 1; i >= 0; i--)


{
swap(&arr[0], &arr[i]);

heapify(arr, i, 0);
}
}
int main()
{

int i, n, arr[25];
printf("Enter the total number of elements: ");
scanf("%d", &n);
printf("Enter the element of array: \n");
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
heapSort(arr, n);
printf("Sorted array: ");
for (i = 0; i < n; i++)
{
printf(" %d\t", arr[i]);
}
}
Output:

4. RESULT & DISCUSSION:


Program was implementation of heap sort where array of size 10 with unsorted element
was input and it successfully sorted the array in ascending form.

5. CONCLUSION:
Hence, divide and conquer sorting algorithm heap sort was successfully created and
implemented using c program
LAB 3: DYNAMIC PROGRAMING

EXPERIMENT 1: TO DESIGN AND IMPLEMENT LONGEST COMMON


SUBSEQUENCES PROBLEM.

1. OBJECTIVE:
• To study the Longest Common Subsequences Problem,
• To implement the Longest Common Subsequences Problem. in c program

2. THEORY:
Longest Common Subsequences Problem.:
Given two sequences, find the length of longest subsequence present in both of them. A
subsequence is a sequence that appears in the same relative order, but not necessarily
contiguous. For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg” etc. are subsequences of
“abcdefg”.
If a set of sequences are given, the longest common subsequence problem is to find a
common subsequence of all the sequences that is of maximal length. Let X = < x1, x2,
x3,…, xm > and Y = < y1, y2, y3,…, yn > be the sequences.
Algorithm:
1) Create a table of dimension n+1*m+1 where n and m are the lengths of X and
Y respectively. The first row and the first column are filled with zeros. Initialize a table.
2) Fill each cell of the table using the following logic.
3) If the character corresponding to the current row and current column are matching, then
fill the current cell by adding one to the diagonal element. Point an arrow to the diagonal
cell.
4) Else take the maximum value from the previous column and previous row element for
filling the current cell. Point an arrow to the cell with maximum value. If they are equal,
point to any of them. Fill the values.
5) Step 2 is repeated until the table is filled. Fill all the values.
6) The value in the last row and the last column is the length of the longest common
subsequence. The bottom right corner is the length of the LCS.
7) In order to find the longest common subsequence, start from the last element and follow
the direction of the arrow. The elements corresponding to () symbol form the longest
common subsequence. Create a path according to the arrows.

3. IMPLEMENTATION:
PROGRAM :
Source code:
#include <stdio.h>
#include <string.h>

int i, j, m, n, c[20][20];
char x[20], y[20], b[20][20];
void print(int i, int j)
{
if (i == 0 || j == 0)
return;
if (b[i][j] == 'd')
{
print(i - 1, j - 1);
printf("%c", x[i - 1]);
}
else if (b[i][j] == 'u')
print(i - 1, j);
else
print(i, j - 1);
}

void lcs()
{
m = strlen(x);
n = strlen(y);
for (i = 0; i <= m; i++)
c[i][0] = 0;
for (i = 0; i <= n; i++)
c[0][i] = 0;

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


for (j = 1; j <= n; j++)
{
if (x[i - 1] == y[j - 1])
{
c[i][j] = c[i - 1][j - 1] + 1;
b[i][j] = 'd';
}
else if (c[i - 1][j] >= c[i][j - 1])
{
c[i][j] = c[i - 1][j];
b[i][j] = 'u';
}
else
{
c[i][j] = c[i][j - 1];
b[i][j] = 'l';
}
}
}
int main()
{
printf("Enter 1st sequence:");
scanf("%s", x);
printf("Enter 2nd sequence:");
scanf("%s", y);
printf("\nThe Longest Common Subsequence is ");
lcs();
print(m, n);
return 0;
}

Output:

4. RESULT & DISCUSSION:


Program was implementation of Longest Common Subsequences Problem. where two
sequence is given as input an it gives maximum possible sequence between two sequences.

5. CONCLUSION:
Hence, Longest Common Subsequences Problem was successfully created and
implemented using c program
LAB 3: DYNAMIC PROGRAMING

EXPERIMENT 2: TO DESIGN AND IMPLEMENT 0-1 KNAPSACK


PROBLEM.

1. OBJECTIVE:
• To study the 0-1KnapSack Problem,
• To implement the 0-1KnapSack. in c program

2. THEORY:
01KnapSack:
Given weights and values of N items, put these items in a knapsack of capacity W to
get the maximum total value in the knapsack. Similarly, given two integer arrays val[0..N-
1] and wt[0..N-1] which represent values and weights associated with N items respectively.
Also given an integer W which represents knapsack capacity, find out the maximum value
subset of val[] such that the sum of the weights of this subset is smaller than or equal to W.
We cannot break an item, either pick the complete item or don’t pick it (0-1 property).
Algorithm:
1) In a DP[][] table let’s consider all the possible weights from ‘1’ to ‘W’ as the columns
and weights that can be kept as rows.
2) The state DP[i][j] will denote the maximum value of ‘j-weight’ considering all values
from ‘1 to ith’. So, if we consider ‘wi’ (weight in ‘ith’ row) we can fill it in all columns
which have ‘weight values > wi’. Now two possibilities can take place:
• Fill ‘wi’ in the given column.
• Do not fill ‘wi’ in the given column.
3) Now we have to take a maximum of these two possibilities, formally if we do not fill
the ‘ith’ weight in the ‘jth’ column then the DP[i][j] state will be the same as DP[i-1][j]
but if we fill the weight, DP[i][j] will be equal to the value of ‘wi’+ value of the column
weighing ‘j-wi’ in the previous row.
4) So, we take the maximum of these two possibilities to fill the current state.

3. IMPLEMENTATION:
PROGRAM :
Source code:
#include <stdio.h>
int max(int a, int b) { return (a > b) ? a : b; }
int knapSack(int W, int wt[], int val[], int n)
{
if (n == 0 || W == 0)
return 0;
if (wt[n - 1] > W)
return knapSack(W, wt, val, n - 1);
else
return max(
val[n - 1]+ knapSack(W - wt[n - 1], wt, val, n - 1),knapSack(W, wt, val, n - 1));
}
int main()
{ int i;
int val[4], wt[4],W;
for( i=0; i<4;i++){
printf("Enter the value and weight of item %d \t",i+1);
scanf("%d%d",&val[i],&wt[i]);
}
printf("Enter the Size of bag \t");
scanf("%d",&W);
int n = sizeof(val) / sizeof(val[0]);
printf("%d", knapSack(W, wt, val, n));
return 0;
}
Output:

4. RESULT & DISCUSSION:


Program was implementation of 01KnapSack Problem, where two array of value and
weight is given as input and it gives maximum possible profit, we can get in given size
bag.

5. CONCLUSION:
Hence, 0-1 Knapsack Problem was successfully created and implemented using c program.
LAB 3: DYNAMIC PROGRAMING

EXPERIMENT 3: TO DESIGN AND IMPLEMENT MATRIX CHAIN


MULTIPLICATION PROBLEM.

1. OBJECTIVE:
• To study the Matrix Chain Multiplication Problem,
• To implement the Matrix Chain Multiplication. in c program

2. THEORY:
Matrix Chain Multiplication: It is a dynamic programming approach in which previous
output is taken as input for next. Here, chain means one matrix's column is equal to the
second matrix's now. This algorithm does not perform the multiplications, but just
determines the best order in which to perform the multiplications.
Recursive definition of optimal solution:
Let m [i, j] be the minimum number of scalar multiplication needed to compute the matrix
Ai, j.
1) If i=j, the chain consists of just one matrix Ai....i=Ai so no scalar multiplication is
necessary to compute the product. Thus m [i, j] = 0 for i= 1, 2, 3....n.
2) If i<j, we assume that to optimally parenthesize the product we split it between Ak and
Ak+1 where i≤ k ≤j. Then m [i, j] equals the minimum cost for computing the sub-
products Ai, k and Ak+1, j+ cost of multiplying them together. We know Ai has
dimension pi-1*pi, so after computing the product Ai, k and Ak+1,j which takes pi-1
*pk *pj scalar multiplication, we obtain
a. m [i, j] = m [i, k] + m [k + 1, j] + pi-1 *pk *pj
3) There are only (j-1) possible values for 'k' namely k = i, i+1.....j-1. Since the optimal
parenthesization must use one of these values for 'k' we need only check them all to
find the best.
a. So, the minimum cost of parenthesizing the product Ai* Ai+1*
......*Aj becomes

b.
4) To construct an optimal solution, let us define s [i,j] to be the value of 'k' at which we
can split the product Ai Ai+1 .....Aj To obtain an optimal parenthesization i.e. s [i, j] =
k such that:
a. m [i,j] = m [i, k] + m [k + 1, j] + pi-1*pk *pj

3. IMPLEMENTATION:
PROGRAM :
Source code:
#include <limits.h>
#include <stdio.h>
#include <limits.h>
#include <stdio.h>
int MatrixChainOrder(int p[], int i, int j)
{
if (i == j)
return 0;
int k;
int min = INT_MAX;
int count;
for (k = i; k < j; k++)
{
count = MatrixChainOrder(p, i, k)+ MatrixChainOrder(p, k + 1, j)+ p[i - 1] * p[k] *
p[j];
if (count < min)
min = count;
}
return min;
}

int main()
{
int arr[] = { 2,5,3,5,2,3,5 };
int N = sizeof(arr) / sizeof(arr[0]);
printf("Minimum number of multiplications is %d ",
MatrixChainOrder(arr, 1, N - 1));
getchar();
return 0;

}
Output:

4. RESULT & DISCUSSION:


Program was implementation Matrix Chain Multiplication Problem, where array of order
of matrix is given as input an it gives minimum possible matrix multiplication, we can get
in given matrix size.

5. CONCLUSION:
Hence, Matrix Chain Multiplication Problem was successfully created and implemented
using c program
LAB 3: DYNAMIC PROGRAMING

EXPERIMENT 4: TO DESIGN AND IMPLEMENT FLOYD WARSHALL


ALOGORITHM.

1. OBJECTIVE:
• To study the Floyd Warshall Algorithm,
• To implement the Floyd Warshall Algorithm. in c program

2. THEORY:
Floyd-Warshall Algorithm:
Floyd-Warshall Algorithm is an algorithm for finding the shortest path between all the
pairs of vertices in a weighted graph. This algorithm works for both the directed and
undirected weighted graphs. But it does not work for the graphs with negative cycles (where
the sum of the edges in a cycle is negative).

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.
• k is not an intermediate vertex in shortest path from i to j. We keep the value of
D[i][j] as it is.
• k is an intermediate vertex in shortest path from i to j. We update the value of
D[i][j] as D[i][k] + D[k][j] if D[i][j] > D[i][k] + D[k][j].

3. IMPLEMENTATION:
PROGRAM :
Source code:
#include <stdio.h>
#define nV 3 // defining the number of vertices
#define INF 999
void printMatrix(int matrix[][nV]);
void floydWarshall(int graph[][nV]) {
int matrix[nV][nV], i, j, k;
for (i = 0; i < nV; i++)
for (j = 0; j < nV; j++)
matrix[i][j] = graph[i][j];
for (k = 0; k < nV; k++) {
for (i = 0; i < nV; i++) {
for (j = 0; j < nV; j++) {
if (matrix[i][k] + matrix[k][j] < matrix[i][j])
matrix[i][j] = matrix[i][k] + matrix[k][j];
}}}
printMatrix(matrix);
}
void printMatrix(int matrix[][nV]) {
printf("\nThe following matrix shows the shortest distances between every pair of
vertices\n");
for (int i = 0; i < nV; i++) {
for (int j = 0; j < nV; j++) {
if (matrix[i][j] == INF)
printf("%4s", "INF");
else
printf("%4d", matrix[i][j]);
}
printf("\n");
}
}

int main() {
int graph[nV][nV] = { {0, 4, 11},
{6, 0, 2},
{3, INF, 0}
};
floydWarshall(graph);
}
Output:

4. RESULT & DISCUSSION:


Program was implementation Floyd Warshall Algorithm, for shortest path in the graph. A
graph with vertices(nV)=3 was taken and its adjacency matrix was is given as input an it
gives the shortest path in the graph in matrix form.

5. CONCLUSION:
Hence, Floyd Warshall Algorithm was successfully created and implemented using c
program

You might also like