You are on page 1of 104

[Type text]

BENGALURU INDIA

LABORATORY MANUAL

DESIGN AND ANALYSIS OF ALGORITHMS


BTCS14F4700

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY

Name

SRN

Branch

Semester

Section

Academic Year
DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Lab Requirements

Following are the required hardware and software for this Course, which are available in the
laboratory.
 Hardware: Desktop system or Virtual machine in a cloud with Operating System installed. The
Configuration of the systems are Pentium IV Processor with 1 GB RAM and 250 GB Hard Disk
.Desktop systems support dual booting with Windows / Linux Operating System .
 Software: C-compiler.[gcc compiler in Linux Environment (fedora 8 to fedora 20), and Turbo C-
IDE on Windows Environment].

This manual is designed for amateur programmers. It is intended that the learning procedure is
made interactive and interesting. The programs presented here are to be compiled, modified and
enhanced for better performance and efficiency. Every design paradigm is to be clearly understood
and implemented for effective learning.
The Linux and windows environments are used as explained below.

Linux environment: All the programs have been composed using ‘vi’ editor and
compiled/executed with the gcc compiler in Linux environment. The execution steps are as follows:

1.Open vi editor using the shell command


$vi <filename.c>
2. Type in the C-code according to the program logic. Save the program and exit to get shell
command prompt (:wq)
3.Compile the program using gcc compiler using the shell command
$gcc -o exeFileName <filename.c>
4. Execute the program using the following shell command
$./exeFileName

Windows environment: Programs can be edited, compiled and executed using Turbo C/C++ IDE.
All operations like opening a file, saving a file, compiling the program and executing the program
are listed under different menus inside the IDE. Keyboard shortcuts are also available for the
abovementioned operations.
Note: Every lab in the manual includes problem statement, learning outcomes, theoretical
description, algorithm, program, program description, expected results, implementation phase,
simulation of syntax and logical errors, final program with results, assignment given, and viva
question.
Recommendation: Linux environment is preferred for executing the programs composed in this
manual.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 2


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

CONTENTS
Sl. Page
PROBLEM STATEMENT
No No

1a
Implement Sequential Search algorithm to search for a key element in a set of integers.
4
b
Sort a set of elements in ascending order using selection sort algorithm

2 12
Search for a given pattern in a text string using Brute Force String Matching.

3a
Search for a given key in a set of elements using Binary Search algorithm.
18
b
Sort a set of elements in descending order using Merge Sort algorithm.

4 27
Sort a set of elements in ascending order using Quick Sort algorithm.

5a
Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's algorithm
34
b
Find Minimum Cost Spanning Tree of a given undirected graph using Prim's algorithm

6 From a given vertex in a weighted connected graph, find shortest paths to other vertices 44
using Dijikstra’s algorithm
7 51
Design and Implement 0/1 Knapsack problem using Dynamic Programming.

8a
Compute the transitive closure of a given directed graph using Warshall's algorithm
58
b
Implement All-Pairs Shortest Paths Problem using Floyd's algorithm

9a
Obtain the Topological ordering of vertices in a given digraph
67
b
Sort a set of elements in ascending order using Insertion Sort algorithm.

10 a
Check whether a given graph is connected or not using DFS method
76
b
Print all the nodes reachable from a given starting node in a digraph using BFS method.

11 a Implement Horspool algorithm for String Matching and find the number of key comparisons
in successful search and unsuccessful search 87
b Sort a given set of elements in ascending order which has duplicate entries. Use the sorting
by counting algorithm
12 a
Implement N Queen's problem using Back Tracking.
Find a subset of a given set S = {sl,s2,.....,sn} of n positive integers whose sum is equal to a 95
b given positive integer d.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 3


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Program 1
1 Problem Statement

a. Implement Sequential Search algorithm to search for a key element in a set of integers.
b. Sort a set of elements in ascending order using selection sort algorithm.

2 Student Learning Outcomes

After successful completion of this session, the student will able to:
 Understand / implement searching and sorting algorithms.
 Understand / apply Brute Force method of implementing algorithms.

3 Design
3.1 Theory

Brute force is a straightforward approach to solving a problem, usually directly based on the problem
statement and definitions of the concepts involved.

SEQUENTIAL SEARCH

Compares successive elements of a given list with a given search key until either a match is encountered
(successful search) or the list is exhausted without finding a match (unsuccessful search).

SELECTION SORT

 We start selection sort by scanning the entire given list to find its smallest element and exchange it
with the first element, putting the smallest element in its final position in the sorted list.
 Then we scan the list, starting with the second element, to find the smallest among the last n − 1
elements and exchange it with the second element, putting the second smallest element in its final
position.
 On the i th pass through the list, which we number from 0 to n − 2, the algorithm searches for the
smallest item among the last n − i elements and swaps it with Ai.
 After n-1 passes the list is sorted.
3.2 Algorithm
ALGORITHM SequentialSearch2 (A [0 ...n], K)
//Implements sequential search with a search key as a sentinel
//Input: An array A of n elements and a search key K
//Output: The index of the first element in A [0... n − 1] whose value is
// equal to K or −1 if no such element is found
1. A[n] ← K
2. i ←0
3. while A[ i] != K do
i←i+1
4. if i < n return i
else return −1.
Explanation of the Algorithm:
 Line 1 assigns the Key element to the nth position of the array.
 Line 2 start the search from index i=0.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 4


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

 Line 3 compares Key element with each array element and repeat till key found.
 Line 4 compares if element is found in i=0 to n-1 indexes then key found at ith location otherwise
key is not found.

ALGORITHM SelectionSort(A[0 ..n − 1] )


//Sorts a given array by selection sort
//Input: An array A[0.. n − 1] of orderable elements
//Output: Array A[0.. n − 1] sorted in non-decreasing order
1. for i ←0 to n − 2 do
2. min← i
3. for j ← i + 1 to n − 1 do
if A[ j ] <A[ min]
min← j
swap A[ i] and A[ min]
Explanation of the Algorithm:
 Line 1 loops for n-1 passes.
 Line 2 assigns minimum to position i.
 Line 3 loops until minimum element is found and swaps it with ith element.
.
3.3 Coding using C Language
1.
Sequential Search

1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(void)
4. {
5. int array[10],index=0,search_element;
6. int n;
7. printf("---------------------------------------\n");
8. printf(" Sequential Search Algorithm \n");
9. printf("---------------------------------------\n");
10. printf("\nEnter the size of array\n");
11. scanf("%d",&n);
12. printf("--------------------------------------\n");
13. printf("\nEnter the Elements in the array\n");
14. printf("--------------------------------------\n");
15. for(index=0;index<n;index++)
16. {
17. scanf("%d",&array[index]);
18. }
19. printf("---------------------------------------\n");
20. printf("\nEnter the element to be searched:");
21. scanf("%d",&search_element);
22. for(index=0;index<n;index++)
23. {
24. if(array[index]==search_element)
25. {
26. printf("\nElement %d found at position %d",array[index],index+1);
27. exit(0);

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 5


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

28. }
29. }
30. printf("\nElement %d is not present",search_element);
31. }

Explanation of Program:
 Lines 1 and 2 include header files that support standard functions in C language.
 Lines 5 and 6 are for variable declaration.
 Lines 22 to 29 perform sequential search.
 Line 26 shows result for successive search and line 30 for unsuccessful search.

Selection Sort
1. #include<stdio.h>
2. int main()
3. {
4. int n,i,j,temp,a[20];
5. printf("Enter total elements: ");
6. scanf("%d",&n);
7. printf("Enter %d elements: ",n);
8. for(i=0;i<n;i++)
9. {
10. scanf("%d",&a[i]);
11. }
12. for(i=0;i<n-1 ; i++)
13. {
14. min=a[i];
15. pos=i;
16. for(j=i+1;j<n ;j++)
17. {
18. if(a[j]<a[i])
19. {
20. min=a[j];
21. pos=j;
22. }
23. }
24. a[pos]=a[i];
25. a[i]=min;
26. }
27. printf("After sorting is: \n");
28. for(i=0;i<n;i++)
29. printf(" %d",a[i]);
30. return 0;
31. }

Explanation of Program:
 Line 1 includes header file that support standard functions in C language.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 6


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

 Line 4 is for variable declaration.


 Lines 12 to 26 perform selection sort.
 Lines 28 and 29 display the sorted array.

3.4 Expected Results


OUTPUT: Sequential Search

reva@reva1:~/Desktop/ada_manual$ vi pgm1a.c
reva@reva1:~/Desktop/ada_manual$ cc pgm1a.c
reva@reva1:~/Desktop/ada_manual$ ./a.out
---------------------------------------
Sequential Search Algorithm
---------------------------------------
Enter the size of array 5
--------------------------------------
Enter the Elements in the array
--------------------------------------
56 45 34 12 90
---------------------------------------
Enter the element to be searched:45

Element 45 found at position 2

OUTPUT: Selection Sort

reva@reva1:~/Desktop/ada_manual$ vi pgm1b.c
reva@reva1:~/Desktop/ada_manual$ cc pgm1b.c
reva@reva1:~/Desktop/ada_manual$ ./a.out
Enter total elements: 5
Enter 5 elements: 67 34 89 23 23
After sorting is:
23 23 34 67 89
3.5 Implementation Phase: Compile the Program and note the syntax errors/warning if occurred during
each compilation. Remove those syntax errors/warnings for generation of executable file.

3.6 Simulation of Errors/Warnings:


3.6.1 Syntax Errors/Warnings:

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 7


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

S. No. Errors/Warnings Reflection of the Errors/Warnings in compilation/output


Simulated

3.6.2 Logical Errors:


S. No. Error Simulated Reflection of the error in compilation/output

4 Final Program and Results

Actual Output Obtained

5 Assignment

5.1 Design of the Program : Bubble Sort


5.1.1 Algorithm

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 8


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

5.1.2 Coding in C Language

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 9


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

5.1.3 Actual Output Obtained

5.1.4 Implementation Phase: Compile the Program and note the syntax errors/warnings occurring during
each compilation. Remove the syntax errors/warnings for generation of executable file.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 10


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Viva Questions

1) How does sequential search works?

2) Derive an exact formula in n (not big O) for the average number of target-to-element
comparisons for successful searches on an array of size n, assuming that all possibilities of
successful match are equally like. Show your work.

3) What is the worst case complexity for selection sort algorithm? Derive.

4) What is the output of selection sort after the 1st iteration given the following sequence of
numbers: 14 9 4 18 45 2 37 63

5) In a selection sort of n elements, how many times is the swap function called in the complete
execution of the algorithm?

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 11


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Program 2
1 Problem Statement

Search for a given pattern in a text string using Brute Force String Matching.

2 Student Learning Outcomes

After successful completion of this session, the student will able to:
 Understand / implement searching and sorting in strings.
 Design algorithms with strings as input and string handling functions.

3 Design
3.1 Theory
STRING MATCHING

 Given a string of n characters called the text and a string of m characters (m ≤ n) called the pattern;
find a substring of the text that matches the pattern.
 To find i—the index of the leftmost character of the first matching substring in the text—such that
t i = p 0 , . . . , t i+j = p j , . . . , t i+m-1 = p m-1 :

 If matches other than the first one need to be found, a string-matching algorithm can simply continue
working until the entire text is exhausted.
 Align the pattern against the first m characters of the text and start matching the corresponding pairs
of characters from left to right until either all the m pairs of the characters match (then the algorithm
can stop) or a mismatching pair is encountered.
 The last position in the text that can still be a beginning of a matching substring is n − m(provided the
text positions are indexed from 0 to n − 1). Beyond that position, there are not enough characters to
match the entire pattern; hence, the algorithm need not make any comparisons there.

3.2 Algorithm
ALGORITHM BruteForceStringMatch (T [0 ..n − 1] , P[0 ..m − 1] )
//Implements brute-force string matching
//Input: An array T [0 ...n − 1] of n characters representing a text and
// an array P [0 ..m − 1] of m characters representing a pattern
//Output: The index of the first character in the text that starts a
// matching substring or −1 if the search is unsuccessful
1. for i ←0 to n − m do
2. j ←0
3. while j <m and P[ j ]= T [ i + j ] do
j←j+1
4. if j = m return i
return −1.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 12


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Explanation of the Algorithm:


 Line 1 loops through the Text String.
 Line 2 initializes the pattern string counter to 0.
 Line 3 compares Text and Pattern Strings index by index
 Line 4 compares if all characters match in the pattern to the text and report search successful at i
Otherwise Pattern not found.

3.3 Coding using C Language


1. #include <stdio.h>
2. #include <string.h>
3. define MAX 100
4. /* try to find the given pattern in the search string */
5. int bruteForce(char *search, char *pattern, int slen, int plen)
6. {
7. int i, j, k;
8. for (i = 0; i <= slen - plen; i++)
9. {
10. for (j = 0, k = i; (search[k] == pattern[j]) && (j < plen); j++, k++);
11. if (j == plen)
12. return j;
13. }
14. return -1;
15. }
16. int main()
17. {
18. char searchStr[MAX], pattern[MAX];
19. int res;
20. printf("Enter Search String:");
21. fgets(searchStr, MAX, stdin);
22. printf("Enter Pattern String:");
23. fgets(pattern, MAX, stdin);
24. searchStr[strlen(searchStr) - 1] = '\0';
25. pattern[strlen(pattern) - 1] = '\0';
26. res = bruteForce(searchStr, pattern, strlen(searchStr), strlen(pattern));
27. if (res == -1)
28. {
29. printf("Search pattern is not available\n");
30. }
31. else
32. {
33. printf("Search pattern available ");
34. }
35. return 0;
36. }

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 13


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Explanation of Program:
 Line 1 includes header file that support standard functions in C language.
 Lines 5 to 15 perform string matching.
 Line 7, 18 and 19 are for variable declaration.
 Line 26 calls the string matching routine.
 Lines 29 and 33 display search results unsuccessful and successful respectively

3.4 Expected Results

OUTPUT:
reva@reva1:~/Desktop/ada_manual$ vi pgm1b.c
reva@reva1:~/Desktop/ada_manual$ vi pgm02.c
reva@reva1:~/Desktop/ada_manual$ cc pgm02.c
reva@reva1:~/Desktop/ada_manual$ ./a.out
Enter Search String: Gods must be crazy

Enter Pattern String: crazy

Search pattern available


Implementation Phase: Compile the Program and note the syntax errors/warning if occurred
3.5
during each compilation. Remove those syntax errors/warnings for generation of executable file.

3.6 Simulation of Errors/Warnings:


3.6.1 Syntax Errors/Warnings:
Errors/Warnings Reflection of the Errors/Warnings in compilation/output
S. No. Simulated

3.6.2 Logical Errors:


S. No. Error Simulated Reflection of the error in compilation/output

4 Final Program and Results

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 14


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Actual Output Obtained

5 Assignment

5.1 Search for a given pattern in a text and replace it with the desired new pattern.
5.1.1 Algorithm

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 15


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

5.1.2 Coding in C Language

5.1.3 Actual Output Obtained

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 16


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Implementation Phase: Compile the Program and note the syntax errors/warnings occurring
5.1.4
during each compilation. Remove the syntax errors/warnings for generation of executable file.

Viva Questions

1) Carry out the empirical analysis of the brute force string matching algorithm on large sizes of
text
file and compare the results with the theoretical average case. Comment on the results.

2) What is the best, average and worse case inputs for brute force string matching? Justify.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 17


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Program 3
1 Problem Statement
a. Search for a given key in a set of elements using Binary Search algorithm
b. Sort a set of elements in descending order using Merge Sort algorithm.
2 Student Learning Outcomes

After successful completion of this session, the student will able to:
 Understand divide and conquer technique.
 Implement and analyze algorithms based on divide and conquer paradigm.

3 Design
3.1 Theory

BINARY SEARCH
 Works by comparing a search key K with the array’s middle element A[m[. if they match, the
algorithm stops. Else, the same operation is repeated recursively for the first half of the array if K<
A[m], and for second half if K>A[m].
 Necessary condition for binary search is that the array must be sorted.

MERGESORT
 It sorts a given array A [0 ...n − 1] by dividing it into two halves A [0 ... _ n/ 2_ − 1] and A [_ n/ 2_
...n − 1], sorting each of them recursively, and then merging the two smaller sorted arrays into a single
sorted one.
The merging of two sorted arrays can be done as follows:
 Two pointers (array indices) are initialized to point to the first elements of the arrays being merged.
 The elements pointed to are compared, and the smaller of them is added to a new array being
constructed;
 After that, the index of the smaller element is incremented to point to its immediate successor in the
array it was copied from.
 This operation is repeated until one of the two given arrays is exhausted, and then the remaining
elements of the other array are copied to the end of the new array.

3.2 Algorithm
ALGORITHM BinSearchl(x, n, a[])

1. low := 1; high := n + 1;
2. while (low < (high — 1)) do
{
3. mid := [(low + high)/2
4. if (x < a[mid]) then high := mid;
else low := mid; // x > a[mid]
}
5. if (x = a[low]) then return low; // x is present.
else return 0;

Explanation of the Algorithm:


 Line 1initializes low and high indexes. Low is index 0 and high is one more than last index.
 Line 2compares the boundaries of the array and index is within the limits.
 Line 3 identifies the middle index.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 18


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

 Line 4 checks if search element is in the first half of the array or second half and
increments/decrements the indexes accordingly.

ALGORITHM Mergesort(A[0 ..n − 1] )


//Sorts array A[0 ..n − 1] by recursive mergesort
//Input: An array A[0 ..n − 1] of orderable elements
//Output: Array A[0 ..n − 1] sorted in nondecreasing order
1. if n > 1
2. copy A[0 .. _ n/ 2_ − 1] to B[0 .. _ n/ 2_ − 1]
3. copy A[_ n/ 2_ ..n − 1] to C[0 .. _ n/ 2_ − 1]
4. Mergesort(B[0 .. _ n/ 2_ − 1] )
5. Mergesort(C[0 .. _ n/ 2_ − 1] )
6. Merge(B, C, A) //see below

ALGORITHM Merge(B[0 ..p − 1] , C[0 ..q − 1] , A[0 ..p + q − 1] )


//Merges two sorted arrays into one sorted array
//Input: Arrays B[0 ..p − 1] and C[0 ..q − 1] both sorted
//Output: Sorted array A[0 ..p + q − 1] of the elements of B and C
1. i ←0; j ←0; k←0 // Initialize the indexes of arrays to be merged
2. while i <p and j <q do // Compare values in array B and C. Lesser value copy to array A
if B[ i]≤ C[ j ]
A[ k]← B[ i]; i ← i + 1
else A[ k]← C[ j ]; j ← j + 1
k← k + 1
3. if i = p
copy C[ j..q − 1] to A[ k..p + q − 1]
else
copy B[ i..p − 1] to A[ k..p + q − 1].

Explanation of the Algorithm:

In the MergeSort routine


 Line 1 checks for the condition if array has more than one element.
 Line 2 and 3 copy the first and second half of the array into buffer arrays.
 In Line 4 and 5 recursively execute lines 1 to 3 on the buffer arrays.
 Line 6 merges the sorted buffer arrays into one sorted array.

In the Merge routine


 Line 1 is for initializing the starting indexes of the buffer and final sorted arrays.
 Line 2 loops until the two buffer arrays are sorted and merged into a single array by comparing the
values index by index in the buffer arrays
 Line 3 copies remaining elements to the final array.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 19


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

3.3 Coding using C Language


Binary Search

1. #include<stdio.h>
2. int main(){
3. int a[10],i,n,m,c=0,l,u,mid;
4. printf("Enter the size of an array: ");
5. scanf("%d",&n);
6. printf("Enter the elements in ascending order: ");
7. for(i=0;i<n;i++)
8. {
9. scanf("%d",&a[i]);
10. }
11. printf("Enter the number to be search: ");
12. scanf("%d",&m);
13. l=0,u=n-1;
14. while(l<=u)
15. {
16. mid=(l+u)/2;
17. if(m==a[mid])
18. {
19. c=1;
20. break;
21. }
22. else if(m<a[mid])
23. {
24. u=mid-1;
25. }
26. else
27. l=mid+1;
28. }
29. if(c==0)
30. printf("The number is not found.");
31. else
32. printf("The number is found.");
33. return 0;
34. }

Explanation of Program:
 Line 1 includes header file that support standard functions in C language.
 Line 3 is for variable declaration.
 Lines 14 to 28 executes binary search.
 Lines 30 and 32 display unsuccessful and successful searches.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 20


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Merge Sort

1. #include<stdio.h>
2. #define MAX 50
3. void mergeSort(int arr[],int low,int mid,int high);
4. void partition(int arr[],int low,int high);
5. int main()
6. {
7. int merge[MAX],i,n;
8. printf("Enter the total number of elements: ");
9. scanf("%d",&n);
10. printf("Enter the elements which to be sort: ");
11. for(i=0;i<n;i++)
12. {
13. scanf("%d",&merge[i]);
14. }
15. partition(merge,0,n-1);
16. printf("After merge sorting elements are: ");
17. for(i=0;i<n;i++)
18. {
19. printf("%d ",merge[i]);
20. }
21. return 0;
22. }
23. void partition(int arr[],int low,int high)
24. {
25. int mid;
26. if(low<high)
27. {
28. mid=(low+high)/2;
29. partition(arr,low,mid);
30. partition(arr,mid+1,high);
31. mergeSort(arr,low,mid,high);
32. }
33. }
34. void mergeSort(int arr[],int low,int mid,int high){
35. int i,m,k,l,temp[MAX];
36. l=low;
37. i=low;
38. m=mid+1;
39. while((l<=mid)&&(m<=high))
40. {
41. if(arr[l]<=arr[m])
42. {
43. temp[i]=arr[l];
44. l++;
45. }
46. else
47. {
48. temp[i]=arr[m];
49. m++;
50. }

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 21


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

51. i++;
52. }
53. if(l>mid)
54. {
55. for(k=m;k<=high;k++)
56. {
57. temp[i]=arr[k];
58. i++;
59. }
60. }
61. else
62. {
63. for(k=l;k<=mid;k++)
64. {
65. temp[i]=arr[k];
66. i++;
67. }
68. }
69. for(k=low;k<=high;k++)
70. {
71. arr[k]=temp[k];
72. }
73. }

Explanation of Program:
 Line 1 includes header file that support standard functions in C language.
 Line 15 calls the partition () routine responsible for splitting the array.
 Lines 31 calls the merge () routine that merges the array after sorting.

3.4 Expected Results


Binary search

reva@reva1:~/Desktop/ada_manual$ vi pgm3a.c
reva@reva1:~/Desktop/ada_manual$ cc pgm3a.c
reva@reva1:~/Desktop/ada_manual$ ./a.out
Enter the size of an array: 5
Enter the elements in ascending order:
10 12 34 56 67
Enter the number to be search: 67
The number is found.

Merge Sort

reva@reva1:~/Desktop/ada_manual$ vi pgm3b.c
reva@reva1:~/Desktop/ada_manual$ cc pgm3b.c
reva@reva1:~/Desktop/ada_manual$ ./a.out
Enter the total number of elements:
12
Enter the elements which to be sort:
12 23 34 32 11 9 5 5 3 1 4 9

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 22


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

After merge sorting elements are: 1 3 4 5 5 9 9 11 12 23 32 34

3.5 Implementation Phase: Compile the Program and note the syntax errors/warning if occurred
during each compilation. Remove those syntax errors/warnings for generation of executable file.

3.6 Simulation of Errors/Warnings:


3.6.1 Syntax Errors/Warnings:
S. No. Errors/Warnings Reflection of the Errors/Warnings in compilation/output
Simulated

3.6.2 Logical Errors:


S. No. Error Simulated Reflection of the error in compilation/output

4 Final Program and Results

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 23


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Actual Output Obtained

5 Assignment

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 24


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Conduct Empirical Analysis of the merge sort routine and comment on the results with
5.1
graphs.
5.1.2 Coding in C Language

5.1.3 Actual Output Obtained

5.1.4 Implementation Phase: Compile the Program and note the syntax errors/warnings occurring
during each compilation. Remove the syntax errors/warnings for generation of executable file.

Viva Questions:

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 25


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

1) What is time complexity of Binary Search?

2) Can Binary Search be used for linked lists?

.
3) How does Binary Search work?

4) What is the best, average and worst case inputs of Merge sort routine?

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 26


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Program 4
1 Problem Statement
Sort a set of elements in ascending order using Quick Sort algorithm.

2 Student Learning Outcomes

After successful completion of this session, the student will able to:
 Understand divide and conquer technique.
 Implement and analyze algorithms based on divide and conquer paradigm.
3 Design
3.1 Theory

 Divides the input’s elements according to their value.


 It rearranges elements of a given array A[0….n-1] to achieve its partition, a situation where all the
elements before some position s are smaller than or equal to A[s] and all the elements after position s
are greater than or equal to A[s]

 After a partition is achieved, A[ s] will be in its final position in the sorted array, and we can continue
sorting the two sub-arrays to the left and to the right of A[ s] independently.
3.2 Algorithm
ALGORITHM Quicksort(A[ l..r] )
//Sorts a subarray by quicksort
//Input: Subarray of array A[0 ..n − 1] , defined by its left and right
// indices l and r
//Output: Subarray A[ l..r] sorted in nondecreasing order
1. if l < r
2. s ← Partition(A[ l..r] )
3. Quicksort(A[ l..s − 1] )
4. Quicksort(A[ s + 1 ..r] )
ALGORITHM HoarePartition(A[ l..r] )
//Partitions a subarray by Hoare’s algorithm, using the first element
// as a pivot
//Input: Subarray of array A[0 ..n − 1] , defined by its left and right
// indices l and r (l<r)
//Output: Partition of A[ l..r], with the split position returned as
// this function’s value
1. p← A[ l]
2. i ← l; j ← r + 1
3. repeat
repeat i ← i + 1 until A[ i]≥ p
repeat j ← j − 1 until A[ j ]≤ p
swap (A[ i] , A[ j ] )
until i ≥ j
4. swap (A[ i] , A[ j ] ) //undo last swap when i ≥ j
5. swap (A[ l] , A[ j ] )
return j.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 27


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Explanation of the Algorithm:

In the QuickSort routine:


 Line 1 checks for the condition if array boundaries are crossed.
 Line 2 calls the partition routine to divide the array into two. One consisting of elements lesser than
the pivot and the second with elements greater than pivot (lines 6 to 10).
 Line 3 and 4 recursively execute the previous step on the first and second parts of the array.

In the partition routine


 Line 1, pivot is assigned as the first value of the array.
 In Line 2 the low and high indexes are assigned to two index pointers that point to the beginning
and end of the array.
 Line 3 repeatedly increments i until a greater element is found and decrements j until a lesser
element is found .Then the index elements of i and j are Swapped.
 Line 4 swaps back the values if the index pointers have crossed.
 Line 5 swaps the pivot to its index in the sorted array.

3.3 Coding using C Language


1. #include<stdio.h>
2. # include<math.h>
3. #define max 500
4. void qsort(int [],int,int);
5. int partition(int [],int,int);
6. int main()
7. {
8. int a[max],i,n;
9. printf("Enter the value of n:\n");
10. scanf("%d",&n);
11. for(i=0;i<n;i++)
12. a[i]=rand()%100;
13. printf("\nThe array elements before\n");
14. for(i=0;i<n;i++)
15. printf("%d\t",a[i]);
16. qsort(a,0,n-1);
17. printf("\nElements of the array after sorting are:\n");
18. for(i=0;i<n;i++)
19. printf("%d\t",a[i]);
20. }
21. void qsort(int a[],int low,int high)
22. {
23. int j;
24. if(low<high)
25. {
26. j=partition(a,low,high);
27. qsort(a,low,j-1);
28. qsort(a,j+1,high);
29. }
30. }
31. int partition(int a[], int low,int high)
SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 28
DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

32. {
33. int pivot,i,j,temp;
34. pivot=a[low];
35. i=low+1;
36. j=high;
37. while(1)
38. {
39. while(pivot>a[i] && i<=high)
40. i++;
41. while(pivot<a[j])
42. j--;
43. if(i<j)
44. {
45. temp=a[i];
46. a[i]=a[j];
47. a[j]=temp;
48. }
49. else
50. {
51. temp=a[j];
52. a[j]=a[low];
53. a[low]=temp;
54. return j;
55. }
56. }
57. }
Explanation of Program:
 Line 1 and 2 includes header files that support standard functions in C language.
 Line 16 calls the qsort() routine responsible for sorting the array.
 Line 26 calls the partition() routine that splits the array.
 Lines 37 to 56 perform the core partition of array as elements before s are lesser than pivot and
elements after are greater than pivot.

3.4 Expected Results

Enter the value of n: 5


The array elements before 11 12 9 1 3
Elements of the array after sorting are: 1 3 9 11 12

3.5 Implementation Phase: Compile the Program and note the syntax errors/warning if occurred during
each compilation. Remove those syntax errors/warnings for generation of executable file.

3.6 Simulation of Errors/Warnings:

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 29


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

3.6.1 Syntax Errors/Warnings:


S. No. Errors/Warnings Reflection of the Errors/Warnings in compilation/output
Simulated

3.6.2 Logical Errors:


S. No. Error Simulated Reflection of the error in compilation/output

4 Final Program and Results

Actual Output Obtained

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 30


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

5 Assignment

5.1 Design of the Program : Perform the Empirical Analysis of the Quick sort routine and map
the results on a graph sheet. Comment on the results.
5.1.1 Coding in C Language

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 31


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

5.1.3 Actual Output Obtained

5.1.4 Implementation Phase: Compile the Program and note the syntax errors/warnings occurring
during each compilation. Remove the syntax errors/warnings for generation of executable file.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 32


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Viva Questions

1) What is the average case complexity for quick sort algorithm?

2) What is the worst case complexity for quick sort algorithm?

3) Which sorting technique is also called partition exchange sort?

4) How does quick sort work?

5) What is the output of quick sort after the 2nd iteration given the following sequence of
numbers: 65 70 75 80 85 60 55 50 45

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 33


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Program 5
1 Problem Statement
a. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's algorithm

b. Find Minimum Cost Spanning Tree of a given undirected graph using Prim's algorithm
2 Student Learning Outcomes

After successful completion of this session, the student will able to:
 Understand the undirected graph & spanning tree concepts
 Understand the way to identify the minimum cost spanning tree in a given graph
 Understand the way this algorithm is used to find the minimum cost spanning tree in a given graph.
3 Design
3.1 Theory

Kruskal's algorithm is a minimum-spanning-tree algorithm where the algorithm finds an edge of the least
possible weight that connects any two trees in the forest. It is a greedy algorithm in graph theory as it finds
a minimum spanning tree for a connected weighted graph adding increasing cost arcs at each step.

Kruskal's algorithm (and in particular, the ordered list of formation of links) can be used in Single-
linkage clustering and allow the distance threshold to be chosen after the algorithm has been run.

One could track the number of outstanding clusters as each link is formed, and then choose a target number
of clusters, and stop Kruskal's algorithm when that target number is reached. Single-linkage clustering, in
turn, can be used in spatial segmentation of text paragraphs on a digital image (photograph) of a paper
document, or a page of newspaper.

 AD and CE are the shortest edges, with length 5, and AD has been arbitrarily chosen, so it is
highlighted.
 CE is now the shortest edge that does not form a cycle, with length 5, so it is highlighted as the
second edge.
 The next edge, DF with length 6, is highlighted using much the same method.
 The next-shortest edges are AB and BE, both with length 7. AB is chosen arbitrarily, and is
highlighted. The edge BD has been highlighted in red, because there already exists a path (in green)
between B and D, so it would form a cycle (ABD) if it were chosen.
 The process continues to highlight the next-smallest edge, BE with length 7. Many more edges are
highlighted in red at this stage: BC because it would form the loop BCE, DE because it would form
the loop DEBA, and FE because it would form FEBAD.
 Finally, the process finishes with the edge EG of length 9, and the minimum spanning tree is found.

Prim's algorithm is an algorithm in graph theory that finds a minimum spanning tree for a connected

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 34


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

weighted graph. This means it finds a subset of the edges that forms a tree that includes every vertex,
where the total weight of all the edges in the tree is minimized. The algorithm was discovered in 1930 by
mathematician Vojtěch Jarník and later independently by computer scientist Robert C. Prim in 1957 and
rediscovered by Edsger Dijkstra in 1959. Therefore it is sometimes called the DJP algorithm, the Jarník
algorithm, or the Prim-Jarník algorithm.

Both Prim's algorithm and Kruskal's algorithm are greedy algorithms for finding the Minimum Spanning
Tree. For Prim's algorithm, the graph has to be connected, but that is not true in the case of Kruskal's
algorithm.

In Prim's algorithm, the next edge in the MST shall be the cheapest edge in the current vertex. In Kruskal's
algorithm, we shall choose the cheapest edge, but it may not be in the current vertex.

Prim's algorithm is found to run faster in dense graphs with more number of edges.

Procedure for finding Minimum Spanning Tree


Step1

No. of Nodes 4 5
0 1 2 3

Distance
0 3 1 6 ∞ ∞

Distance From
0 0 0

Step2

No. of Nodes
0 1 2 3 4 5

Distance
0 3 0 5 6 4

Distance From
0 2 2 2

Step3

No. of Nodes
0 1 2 3 4 5
Distance
0 0 0 5 3 4

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 35


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Distance From
2 1 2

Step4

No. of Nodes
0 1 2 3 4 5
Distance
0 0 0 5 0 4
Distance From
2 2

Step5

No. of Nodes Distance

Distance From

Minimum Cost = 1+2+3+3+4 = 13


3.2 Algorithm
KRUSKAL'S ALGORITHM
ALGORITHM Kruskal(G)
//Kruskal’s algorithm for constructing a minimum spanning tree
//Input: A weighted connected graph G = (V, E )
//Output: ET , the set of edges composing a minimum spanning tree of G

1. sort E in non-decreasing order of the edge weights w(ei 1 ) ≤ . . . ≤ w(ei| E| ) ET ←NULL;


2. ecounter ←0 //initialize the set of tree edges and its size
3. k←0 //initialize the number of processed edges
4. while ecounter < | V| − 1 do
5. k← k + 1
6. if ET ∪ { eik} is acyclic
7. ET← ET ∪ { eik};
8. ecounter ← ecounter + 1
9. return ET.

Explanation of the Algorithm:


 Line 1 sort the set of edges in ascending order based on the weight and initialises the output edge
set ET to null.
 Line 2 initializes the edge counter ecounter to zero.
 Line 3 initializes the counter k to zero.
 Lines [4 to 8] builds the output edge set ET, checking for cycle while adding every edge.
 Line 9 displays the output edge set that form the minimum spanning tree.

PRIM'S ALGORITHM

ALGORITHM Prim(G)
//Prim’s algorithm for constructing a minimum spanning tree
//Input: A weighted connected graph G = _ V, E _
//Output: ET , the set of edges composing a minimum spanning tree of G

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 36


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

1. VT←{ v 0} //the set of tree vertices can be initialized with any vertex ET←NULL;
2. for i ←1 to | V| − 1 do
3. find a minimum-weight edge e* = (v*, u*) among all the edges (v, u) such that v is in VT
and u is in V − VT
4. VT← VT ∪ { u*}
5. ET← ET ∪ { e*}
6. return ET.

Explanation of the Algorithm:


 Line 1 initializes the output edge set of tree ET to NULL.
 Lines [2 to 5] start a for loop to find the minimum-weight edge among all the edges in the tree.
 Line 6 displays the set of edges that forms the minimum spanning tree.

3.3 Coding using C Language

Kruskal's Method

1. #include<stdio.h>
2. int i,j,k,a,b,v,u,n,ne=1; /* Variables declaration & initialization */
3. int min,mincost=0,cost[9][9],parent[9]; /* Arrays declaration */
4. void main()
5. {
6. printf("\nEnter the number of vertices\n");
7. scanf("%d",&n); /* First input to the program */
8. printf("Enter the cost of matrix::\n"); /* Second input to the program */
9. for (i=1;i<=n;i++)
10. for (j=1;j<=n;j++)
11. {
12. scanf("%d",&cost[i][j]);
13. if(cost[i][j]==0) /* Check whether cost is 0 */
14. cost[i][j]=999; /* if cost is 0, set it to 999 */
15. }
16. printf("\nThe edges of spanning tree are: \n\n");
17. while(ne<n)
18. {
19. for (i=1,min=999;i<=n; i++)
20. for (j=1;j<=n;j++)
21. {
22. if(cost[i][j]<min) /* Check whether cost of the edge is less than 999 */
23. {
24. min=cost[i][j]; /* Set the min to the cost of the edge */
25. a=u=i; /* Set the value of a & u equal to i */
26. b=v=j; /* Set the value of b & v equal to j */
27. }
28. }
29. while(parent[u])
30. u=parent[u];
31. while(parent[v])
32. v=parent[v];
33. if(u!=v)
34. {
35. printf("\n%d\tEdge(%d,%d)=%d",ne++,a,b,min);

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 37


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

36. mincost+=min; /* reset mincost equal to sum of previous mincost and min */
37. parent[v]=u;
38. }
39. cost[a][b]=cost[b][a]=999;
40. }
41. printf("\n\tMiINCOST=%d\n",mincost);
42. }

Explanation of Program:
 Line 1 includes header file that support standard functions in C language.
 Lines 9 to 15 are to input the cost matrix and to initialize the cost matrix.
 Lines 17 to 40 find the minimum spanning tree and the minimum cost of the spanning tree.
 Line 41 displays the minimum cost of the spanning tree.

Prim's Method
1. #include<stdio.h>
2. int i, j, a, b, v, u,n, ne=1;
3. int min,mincost=0, cost[9][9], visited[9];
4. main()
5. {
6. printf( "The no of vertices=\t");
7. scanf("%d",&n);
8. printf("The cost of matrix=\t");
9. for( i=1;i<=n;i++)
10. for( j=1;j<=n;j++)
11. {
12. scanf("%d",&cost[i][j]);
13. if(cost[i][j]==0) cost[i][j]=999;
14. }
15. printf("The edges of spanning tree are \t");
16. visited[1]=1;
17. while(ne<n)
18. {
19. for(i=1,min=999;i<=n; i++)
20. {
21. for(j=1;j<=n;j++)
22. {
23. if(cost[i][j]<min)
24. {
25. if(visited[i]==0)
26. continue;
27. else
28. {
29. min=cost[i][j];
30. a=u=i;
31. b=v=j;
32. }
33. }
34. }
35. }
36. if(visited[v]==0)
37. {

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 38


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

38. printf("\n%d\t Edge \t(%d, %d)=%d\n",ne++, a, b, min);


39. mincost+=min;
40. visited[b]=1;
41. }
42. cost[a][b]=cost[b][a]=999;
43. }
44. printf("\n\t mincost=%d\n",mincost);
45. }

Explanation of Program:
 Line 1 includes header file that support standard functions in C language.
 Lines 9 to 14 are to input the cost matrix and to initialize the cost matrix.
 Lines 17 to 43 find the minimum spanning tree and the minimum cost of the spanning tree.
 Line 44 displays the minimum cost of the spanning tree.
3.4 Expected Results
Kruskal's Method
Enter the number of vertices
4
Enter the cost of matrix::
0360
0028
0003
0000
The edges of spanning tree are:
1 Edge(2,3)=2
2 Edge(1,2)=3
3 Edge(3,4)=3

MiINCOST=8
Prim's Method
The no of vertices = 4
The cost of matrix
0360
3028
6203
0830

The edges of spanning tree are


1 Edge (1, 2)=3
2 Edge (2, 3)=2
3 Edge (3, 4)=3
mincost=8

3.5 Implementation Phase: Compile the Program and note the syntax errors/warning if occurred
during each compilation. Remove those syntax errors/warnings for generation of executable
file.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 39


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

3.6 Simulation of Errors/Warnings:


3.6.1 Syntax Errors/Warnings:
S. No. Errors/Warnings Reflection of the Errors/Warnings in compilation/output
Simulated

3.6.2 Logical Errors:


S. No. Error Simulated Reflection of the error in compilation/output

4 Final Program and Results

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 40


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Actual Output Obtained

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 41


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

5 Assignment

Analyse the Prim's and Kruskal's Algorithm for large number of vertices . Carry out
5.1
empirical analysis and comment on the running time .Compare the results.
5.1.1 Algorithm

5.1.2 Coding in C Language

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 42


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

5.1.3 Actual Output Obtained

5.1.4 Implementation Phase: Compile the Program and note the syntax errors/warnings occurring
during each compilation. Remove the syntax errors/warnings for generation of executable file.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 43


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Viva Questions

1) What is Minimum Spanning Tree?

2) How many edges does a minimum spanning tree have with 20 nodes?

3) List out the difference between Kruskal’s & Prim’s algorithms.

4) What is the efficiency of Kruskal’s & Prim’s algorithms.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 44


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Program 6
1 Problem Statement
From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijikstra’s
algorithm
2 Student Learning Outcomes

After successful completion of this session, the student will able to:
 Understand the weighted connected graph & spanning tree concepts
 Understand the way to identify the shortest paths in a given graph
 Understand the way this algorithm is used to find the shortest paths between the vertices in a given
graph.
3 Design
3.1 Theory

Dijkstra's algorithm is an algorithm for finding the shortest paths between nodes in a graph, which may
represent, for example, road networks. It was conceived by computer scientist Edsger W. Dijkstra in 1956
and published three years later.

The algorithm exists in many variants; Dijkstra's original variant found the shortest path between two
nodes, but a more common variant fixes a single node as the "source" node and finds shortest paths from
the source to all other nodes in the graph, producing a shortest-path tree.

For a given source node in the graph, the algorithm finds the shortest path between that node and every
other. It can also be used for finding the shortest paths from a single node to a single destination node by
stopping the algorithm once the shortest path to the destination node has been determined. For example, if
the nodes of the graph represent cities and edge path costs represent driving distances between pairs of
cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one
city and all other cities.

As a result, the shortest path algorithm is widely used in network routing protocols, most notably IS-IS
and Open Shortest Path First (OSPF). It is also employed as a subroutine in other algorithms such as
Johnson's.

3.2 Algorithm

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 45


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Let's call the node we are starting with an initial node. Let a distance of a node X be the distance from
the initial node to it. Our algorithm will assign some initial distance values and will try to improve them
step-by-step.

1. Assign to every node a distance value. Set it to zero for our initial node and to infinity for all other
nodes.
2. Mark all nodes as unvisited. Set initial node as current.
3. For current node, consider all its unvisited neighbours and calculate their distance (from the initial
node). For example, if current node (A) has distance of 6, and an edge connecting it with another node
(B) is 2, the distance to B through A will be 6+2=8. If this distance is less than the previously recorded
distance (infinity in the beginning, zero for the initial node), overwrite the distance.
4. When we are done considering all neighbours of the current node, mark it as visited. A visited node
will not be checked ever again; its distance recorded now is final and minimal.
5. Set the unvisited node with the smallest distance (from the initial node) as the next "current node"
and continue from step 3.
6. When all nodes are visited, algorithm ends.
3.3 Coding using C Language
1. #include<stdio.h>
2. main()
3. {
4. int visited[23],i,k,w,v,min;
5. int n,sv,j,dist[10],cost[10][10];
6. printf("\nenter the no of vertices");
7. scanf("%d",&n);
8. printf("enter the cost of matrix:\n");
9. for(i=1;i<=n;i++)
10. for(j=1;j<=n;j++)
11. {
12. scanf("%d",&cost[i][j]);
13. if(cost[i][j]==0)
14. cost[i][j]=999;
15. }
16. printf("enter the source\n");
17. scanf("%d",&sv);
18. for(i=1;i<=n;i++)
19. {
20. visited[i]=0;
21. dist[i]=cost[sv][i];
22. }
23. visited[sv]=1;
24. dist[sv]=1;
25. for(k=2;k<=n;k++)
26. {
27. min=999;
28. for(w=1;w<=n;w++)
29. if(dist[w]<min && visited[w]==0)
30. {
31. min=dist[w];
32. v=w;
33. }
SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 46
DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

34. visited[v]=1;
35. for(w=1;w<=n;w++)
36. if(dist[v]+cost[v][w]<dist[w])
37. dist[w]=cost[v][w]+dist[v];
38. }
39. printf("shortest path\n");
40. for(j=1;j<=n;j++)
41. {
42. if(j!=sv)
43. printf("%d->%d==%d\n",sv,j,dist[j]);
44. }
45. }

Explanation of Program:
 Line 1 includes header file that support standard functions in C language.
 Line 6 accepts the first input that defines the number of vertices in the given graph.
 Lines 9 to 15 are to input the cost matrix.
 Lines 18 to 22 are to initialize the cost matrix.
 Lines 25 to 38 finds single source shortest path to all vertices from a single source.
 Lines 39 to 44 display the shortest path possible.

3.4 Expected Results


Output:
enter the no of vertices
4
enter the cost of matrix:
0350
0000
0002
6700
enter the source
1
shortest path
1->2==3
1->3==5
1->4==7

3.5 Implementation Phase: Compile the Program and note the syntax errors/warning if occurred
during each compilation. Remove those syntax errors/warnings for generation of executable file.

3.6 Simulation of Errors/Warnings:


3.6.1 Syntax Errors/Warnings:

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 47


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

S. No. Errors/Warnings Reflection of the Errors/Warnings in compilation/output


Simulated

3.6.2 Logical Errors:


S. No. Error Simulated Reflection of the error in compilation/output

4 Final Program and Results

Actual Output Obtained

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 48


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

5 Assignment

5.1 Design an algorithm to implement all pairs shortest paths( Use Greedy Technique )
5.1.1 Algorithm

5.1.2 Coding in C Language

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 49


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

5.1.3 Actual Output Obtained

5.1.4 Implementation Phase: Compile the Program and note the syntax errors/warnings occurring
during each compilation. Remove the syntax errors/warnings for generation of executable file.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 50


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Viva Questions

1) What is connected graph?

2) What is weighted graph?

3) What is weighted connected graph?

4) What do mean by shortest path between vertices?

5) Explain the concept of Dijkstra’s algorithm with an example.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 51


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Program 7
1 Problem Statement
Design and Implement 0/1 Knapsack problem using Dynamic Programming.

2 Student Learning Outcomes

After successful completion of this session, the student will able to:
 Understand what is dynamic programming
 Understand the what is Knapsack problem
 Understand the way this algorithm is used to solve the 0/1 Knapsack problem.
3 Design
3.1 Theory
0/1 Knapsack is typical problem which is used to demonstrate application of greedy algorithm as well as
dynamic programming. There are cases when applying greedy algorithm does not give optimal solution.
There are many flavours in which Knapsack problem can be asked.

Example of a one-dimensional (constraint)


knapsack problem: which boxes should be
chosen to maximize the amount of money while
still keeping the overall weight under or equal to
15 kg? A multiple constrained problem could
consider both the weight and volume of the
boxes.
(Solution: if any number of each box is
available, then three yellow boxes and three grey
boxes; if only the shown boxes are available,
then all but the green box.)

1. A thief enters a museum and want to steal artifacts from there. Every artifact has a weight and value
associated with it. Thief carries a knapsack (bag) which can take only a specific weight. Problem is to
find the combination of artifacts thief takes so that he gets maximum value and weight of all the taken
artifacts is less the capacity of the bag he has brought. Thief cannot take any artifact partially. Either he
takes it or leaves it. Hence the problem is 0-1 knapsack.

2. Second flavour is : We have N files each having a size say Si. We have a total storage capacity of W
bytes. For each file to be stored the re-computation cost is Vi. Problem is to store as files on storage that
combined size of all files is less than W and their re-computation value is maximum.

We can either store or leave the file. We cannot store partial file. Hence this is a case of 0-1 knapsack
problem.

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. In other words, 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 sum of the weights of
this subset is smaller than or equal to W. You cannot break an item, either pick the complete item, or
don’t pick it (0-1 property).

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 52


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

A simple solution is to consider all subsets of items and calculate the total weight and value of all
subsets. Consider the only subsets whose total weight is smaller than W. From all such subsets, pick the
maximum value subset.

3.2 Algorithm
Algorithm JS(d,j,n)

1. d[i] >= 1, 1 <= i <= n are the deadlines, n >= 1.


2. The jobs are ordered such that P [1] >= p[2] >= … >= p[n].
3. J[i] is the ith job in the optimal solution, 1 <= i <= k.
4. Also, at termination
5. d[J[i]] <= d[J[i + 1]], 1 <= i <= k. rf[0] := J[0] := 0;
6. Initialize. J[l] := 1;
7. Include job 1. fc:=l; for i := 2 to n
8. Do
9. Consider jobs in non increasing order of p[i].
10. Find position for i and check feasibility of insertion. r := k;
11. while ((d[J[r]] > d[i]) and (d[J[r]] > r))
12. do
13. r := r - 1;
14. if ((d[J[r]] <= d[i]) and (d[i] > r))
15. then
16. Insert i into J[ ].
17. for q := k to (r + 1) step -1
18. do
19. J[q + 1] := J[q];
20. J[r + 1] := i; k := k + 1;
21. return k;
Explanation of the Algorithm:

 Line 1 defines the job in the list.


 Lines [2 to 5] arrange the jobs in descending order.
 Lines [7 to 20] adds jobs one after other in to the bag checking feasibility of insertion
 Line 21 gives the final maximum value of subset k.
3.3 Coding using C Language
1 #include<stdio.h> /* includes header file that support standard functions in C */
2 int v[20][20],values[23],weight[45]; /* Arrays declaration */
3 int max(int m,int n) /* Function max() definition that returns the maximum among m & n */
4 {
5 if(m>=n) return m;
6 else return n;
7 }
8 int knapsack(int i, int j) /* Function knapsack() definition that solves the problem */
9 {
10 int value;
11 if(v[i][j]<0)
12 {
13 if(j-weight[i]>=0)

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 53


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

14 {
15 value=max(knapsack(i-1,j),(values[i]+knapsack(i-1,j-weight[i])));
16 }
17 else
18 {
19 value=knapsack(i-1,j);
20 }
21 v[i][j]=value;
22 }
23 return v[i][j]; /* Solution the given problem */
24 }
25 main() /* Start of main program */
26 {
27 int n,i,j,w,profit;
28 printf("enter the no of elem\n"); /* User input for number of elements */
29 scanf("%d", &n);
30 printf("enter the capacity\n"); /* User input to decide capacity of Knapsack */
31 scanf("%d", &w);
32 printf("enter the weights\n");
33 for(i=1; i<=n; i++)
34 {
35 scanf("%d",&weight[i]); /* User input to weight array */
36 }
37 printf("enter the profits\n");
38 for(i=1;i<=n;i++)
39 {
40 scanf("%d",&values[i]); /* User input to value[] array */
41 }
42 for(i=0;i<=n;i++)
43 for(j=0;j<=w;j++)
44 if(i==0||j==0) v[i][j]=0;
45 else v[i][j]=-1;
46 profit=knapsack(n,w);
47 printf("the value is %d\n",profit); /* Display the output – profit */
48 }

Explanation of Program:
 Line 1 includes header file that support standard functions in C language.
 Line 2 is for variable declaration.
 Lines 8 to 24 solve Knapsack problem.
 Lines 28 to 35 to accept the various user input to the program
 Lines 38 to 46 to calculate the value of profit
 Line 47 displays the output profit value

3.4 Expected Results


enter the no of elements
4
enter the capacity
5
enter the weights
2 1 3 2
enter the profits

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 54


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

12 10 20 15
the value is 37

3.5 Implementation Phase: Compile the Program and note the syntax errors/warning if occurred
during each compilation. Remove those syntax errors/warnings for generation of executable file.

3.6 Simulation of Errors/Warnings:


3.6.1 Syntax Errors/Warnings:
S. No. Errors/Warnings Reflection of the Errors/Warnings in compilation/output
Simulated

3.6.2 Logical Errors:


S. No. Error Simulated Reflection of the error in compilation/output

4 Final Program and Results

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 55


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Actual Output Obtained

5 Assignment

5.1 Design an algorithm to find the Binomial Co-efficient and implement the same.
5.1.1 Algorithm

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 56


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

5.1.2 Coding in C Language

5.1.3 Actual Output Obtained

5.1.4 Implementation Phase: Compile the Program and note the syntax errors/warnings occurring
during each compilation. Remove the syntax errors/warnings for generation of executable file.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 57


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Viva Questions

1) What is dynamic programming?

2) What is Knapsack problem?

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 58


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Program 8
1 Problem Statement
a) Compute the transitive closure of a given directed graph using Warshall's algorithm
b) Implement All-Pairs Shortest Paths Problem using Floyd's algorithm
2 Student Learning Outcomes

After successful completion of this session, the student will able to:
 Understand the meaning of transitive closure
 Understand how to compute the transitive closure for the given graph
 Understand the way this algorithm is used to compute the transitive closure for a given graph.
3 Design
3.1 Theory
Warshall’s algorithm is an efficient method of finding the adjacency matrix of the transitive closure of
relation R on a finite set S from the adjacency matrix of R. It uses properties of the digraph D, in
particular, walks of various lengths in D.

Transitive closure of a graph


Given a directed graph, find out if a vertex j is reachable from another vertex i for all vertex pairs (i, j) in
the given graph. Here reachable mean that there is a path from vertex i to j. The reach-ability matrix is
called transitive closure of a graph.

The graph is given in the form of adjacency matrix say ‘graph[V][V]’ where graph[i][j] is 1 if there is an
edge from vertex i to vertex j or i is equal to j, otherwise graph[i][j] is 0.

Floyd Warshall Algorithm can be used to calculate the distance matrix dist[V][V] using Floyd
Warshall, if dist[i][j] is infinite, then j is not reachable from i, otherwise j is reachable and value of
dist[i][j] will be less than V.

Instead of directly using Floyd Warshall, we can optimize it in terms of space and time, for this
particular problem.

Following are the optimizations:

1) Instead of integer resultant matrix (dist[V][V] in floyd warshall), we can create a boolean reach-
ability matrix reach[V][V] (we save space). The value reach[i][j] will be 1 if j is reachable from i,
otherwise 0.

2) Instead of using arithmetic operations, we can use logical operations. For arithmetic operation ‘+’,
logical and ‘&&’ is used, and for min, logical or ‘||’ is used. (We save time by a constant factor. Time
complexity is same though)

In computer science, the Floyd–Warshall algorithm is an algorithm for finding shortest paths in a
weighted graph with positive or negative edge weights (but with no negative cycles). A single execution
of the algorithm will find the lengths (summed weights) of the shortest paths between all pairs of
vertices, though it does not return details of the paths themselves. Versions of the algorithm can also be
used for finding the transitive closure of a relation R, or (in connection with the Schulze voting system)
widest paths between all pairs of vertices in a weighted graph.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 59


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

At label k=0 above, the only known paths correspond to the single edges in the graph. At k=1, paths
that go through the vertex 1 are found: in particular, the path 2→1→3 is found, replacing the path 2→3
which has fewer edges but is longer. At k=2, paths going through the vertices {1,2} are found. The red
and blue boxes show how the path 4→2→1→3 is assembled from the two known paths 4→2 and
2→1→3 encountered in previous iterations, with 2 in the intersection. The path 4→2→3 is not
considered, because 2→1→3 is the shortest path encountered so far from 2 to 3. At k=3, paths going
through the vertices {1,2,3} are found. Finally, at k=4, all shortest paths are found.
3.2 Algorithm
Warshall’s algorithm

Input: Adjacency matrix A of relation R on a set of n elements


Output: Adjacency matrix T of the transitive closure of R.
Algorithm Body:
1. T := A [initialize T to A]
2. for j := 1 to n
3. for i := 1 to n
4. if T[i, j] = 1 then
5. i a := [i j] a ∨ a [form the Boolean OR of row i and row j, store it in i a ]
6. next i
7. next j
8. end Algorithm Warshall

Explanation of the Algorithm:

 Line 1 initializes the output adjacency matrix T to input matrix A.


 Lines [2 to 7] identify the direct path between the vertices using the Boolean OR function and
construct the output adjacency matrix T.

Floyd's Algorithm

1. FloydAPSP (int N, rmatrix &C, rmatrix &D, imatrix &P)


2. {
3. int i,j,k;
4. for (i = 0; i < N; i++) {
5. for (j = 0; j < N; j++) {
6. D[i][j] = C[i][j];
7. P[i][j] = -1;
8. }
9. D[i][i] = 0.0;
10. }

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 60


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

11. for (k = 0; k < N; k++) {


12. for (i = 0; i < N; i++) {
13. for (j = 0; j < N; j++) {
14. if (D[i][k] + D[k][j] < D[i][j]) {
15. D[i][j] = D[i][k] + D[k][j];
16. P[i][j] = k;
17. }}}}

Explanation of the Algorithm:

 Line 3 declares all the variables


 Lines 4 to 8 initializes the matrix C to matrix D
 Line 9 sets the distance between same vertex 0
 Lines 11 to 17 calculate the distance between every vertex to all other vertices.
 Line 16 constructs the output matrix P.
3.3 Coding using C Language
Warshall algorithm

1 #include<stdio.h>
2 void warshall(int c[10][10],int n)
3 {
4 int i,j,k;
5 for(k=1;k<=n;k++)
6 for(i=1;i<=n;i++)
7 for(j=1;j<=n;j++)
8 c[i][j]=(c[i][j] || (c[i][k] && c[k][j]));
9 }
10 main()
11 {
12 int c[10][10],i,j,n;
13 printf("Enter the numb of veritces\n");
14 scanf("%d",&n);
15 printf("Enter the adjacency matrix\n");
16 for(i=1;i<=n;i++)
17 for(j=1;j<=n;j++)
18 scanf("%d",&c[i][j]);
19 warshall(c,n);
20 printf("The path matrix is\n");
21 for(i=1;i<=n;i++)
22 {
23 for(j=1;j<=n;j++)
24 printf("%d\t",c[i][j]);
25 printf("\n");
26 }
27 }

Explanation of Program:
 Line 1 includes header file that support standard functions in C language.
 Lines 4 and 12 are for variable declaration.
 Lines 2 to 9 implement Warshall’s algorithm.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 61


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

 Lines 15 to 18 to set values to adjacency matrix


 Lines 21 to 25 define the warshall function that prints path matrix

Floyd’s Algorithm

1 #include<stdio.h>
2 #include<omp.h>
3 void floyd(int[10][10],int);
4 int min(int,int);
5
6 void main()
7 {
8 int n,a[10][10],i,j;
9 printf("Enter the no.of nodes :");
10 scanf("%d",&n);
11 printf("\nEnter the cost adjacency matrix\n");
12 for(i=1;i<=n;i++)
13 for(j=1;j<=n;j++)
14 scanf("%d",&a[i][j]);
15 floyd(a,n);
16 }
17
18 void floyd(int a[10][10],int n)
19 {
20 int d[10][10],i,j,k;
21 // #pragma omp parallel for
22 for(i=1;i<=n;i++)
23 {
24 for(j=1;j<=n;j++)
25 d[i][j]=a[i][j];
26 }
27
28 // #pragma omp parallel for
29 for(k=1;k<=n;k++)
30 {
31 for(i=1;i<=n;i++)
32 {
33 for(j=1;j<=n;j++)
34 {
35 d[i][j]=min(d[i][j],d[i][k]+d[k][j]);
36 }
37 }
38 }
39
40 printf("\nThe distance matrix is\n"); //#pragma omp parallel for
41 for(i=1;i<=n;i++)
42 {
43 for(j=1;j<=n;j++)
44 printf("%d\t",d[i][j]);
45 }
46 printf("\n");
47 }
48 }
SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 62
DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

49
50 int min (int a,int b)
51 {
52 if(a<b)
53 return a;
54 else
55 return b;
56 }

Explanation of Program:
 Line 1 includes header file that support standard functions in C language.
 Lines 8 and 20 are for variable declaration.
 Lines 18 to 48 implement Floyd’s algorithm which run in 3 threads parallel.
 Lines 50 to55 define the function min to find out the minimum among the given two input that
find out the minimum distance.
2.
3.4 Expected Results
Warshall algorithm

Enter the numb of veritces


4
Enter the adjacency matrix
0110
0001
0001
0000
The path matrix is
0 1 1 1
0 0 0 1
0 0 0 1
0 0 0 0

Floyd’s Algorithm

Enter the no.of nodes :4


Enter the cost adjacency matrix
0 999 3 999
2 0 999 999
999 7 0 1
6 999 999 0

The distance matrix is

0 10 3 4
2 0 5 6
7 7 0 6
1 6 9 0
3.5 Implementation Phase: Compile the Program and note the syntax errors/warning if occurred
during each compilation. Remove those syntax errors/warnings for generation of executable file.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 63


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

3.6 Simulation of Errors/Warnings:


3.6.1 Syntax Errors/Warnings:
S. No. Errors/Warnings Reflection of the Errors/Warnings in compilation/output
Simulated

3.6.2 Logical Errors:


S. No. Error Simulated Reflection of the error in compilation/output

4 Final Program and Results

Actual Output Obtained

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 64


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

5 Assignment

5.1 Design of the Program : Tower of Hanoi


5.1.1 Algorithm

5.1.2 Coding in C Language

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 65


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

5.1.3 Actual Output Obtained

5.1.4 Implementation Phase: Compile the Program and note the syntax errors/warnings occurring
during each compilation. Remove the syntax errors/warnings for generation of executable file.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 66


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Viva Questions

1) What is directed graph, connected graph?

2) What is adjacency matrix?

3) What is transitive closure?

4) What is the arithmetic, Boolean & logical operators available for programming?

5) Can you find out any difference between Warshall & Floyd algorithms?

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 67


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Program 9
1 Problem Statement
a. Obtain the Topological ordering of vertices in a given digraph.
b. Sort a set of elements in ascending order using Insertion Sort algorithm.
2 Student Learning Outcomes
After successful completion of this session, the student will able to:
 Understand / apply decrease and conquer method of implementing algorithms.
 Describe the basic mechanics of the insertion sort algorithm.
 Critically analyze the performance of the algorithm and identify its weaknesses.

3 Design
3.1 Theory

Topological ordering

 Depth-first search and breadth-first search are principal traversal algorithms for traversing digraphs
as well, but the structure of corresponding forests can be more complex than for undirected graphs.
 A back edge in a DFS forest of a directed graph can connect a vertex to its parent.
 Whether or not it is the case, the presence of a back edge indicates that the digraph has a directed
cycle.
 A directed cycle in a digraph is a sequence of three or more of its vertices that starts and ends with
the same vertex and in which every vertex is connected to its immediate predecessor by an edge
directed from the predecessor to the successor.
 If a DFS forest of a digraph has no back edges, the digraph is a dag, an acronym for directed
acyclic graph.
 We can list its vertices in such an order that for every edge in the graph, the vertex where the edge
starts is listed before the vertex where the edge ends. This problem is called topological sorting.
 Below figure shows the example for topological sorting.

Fig. Topological sorting

Insertion Sort algorithm

To sort an array A[0 ..n − 1].


 We assume that the smaller problem of sorting the array A[0 ..n − 2] has already been solved to
give us a sorted array of size n − 1: A[0]≤ . . . ≤ A[ n−2].
 Find an appropriate position for A[ n − 1] among the sorted elements and insert it there.
SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 68
DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

 This is usually done by scanning the sorted subarray from right to left until the first element
smaller than or equal to A[ n − 1] is encountered to insert A[ n − 1] right after that element. The
resulting algorithm is called straight insertion sort or simply insertion sort.
 Though insertion sort is clearly based on a recursive idea, it is more efficient to implement this
algorithm bottom up, i.e., iteratively.

3.2 Algorithm

Topological ordering of vertices in a given digraph.

Algorithm1:
1) Perform a DFS traversal and note the order in which vertices become dead-ends (i.e., popped off
the traversal stack). Reversing this order yields a solution to the topological sorting problem,
provided, of course, no back edge has been encountered during the traversal.
2) If a back edge has been encountered, the digraph is not a dag, and topological sorting of its
vertices is impossible.

Algorithm2:
Repeatedly, identify in a remaining digraph a source, which is a vertex with no incoming edges, and
delete it along with all the edges outgoing from it. The order in which the vertices are deleted yields
a solution to the topological sorting problem.

Insertion Sort algorithm.

//Sorts a given array by insertion sort


//Input: An array A[0 ..n − 1] of n orderable elements
//Output: Array A[0 ..n − 1] sorted in nondecreasing order
1 for i ←1 to n − 1
2 v ← A[ i]
3 j←i−1
4 while j ≥ 0 and A[ j ] > v
5 A[ j + 1]← A[ j ]
6 j←j−1
7 A[ j + 1]← v

Explanation of Algorithm:
 Line 1-3, copy the ith element of an array to variable v and setting j value as i-1
 Line 4-6, till j>=0 and A[ j ] > v copy the value of A[ j ] to A[ j + 1] and decrement j by 1.
 Lines 7, copy v value to A[j+1].

3.3 Coding using C Language

Topological ordering of vertices in a given digraph.

1 #include<stdio.h>
2 void TopologicalSort();
3 int adj[10][10];
4 int Reach[10],n;
5 int order[10];
6 int m=1;
7 int main()
8 {

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 69


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

9 int i,j;
10 printf("\n\n\tEnter how many vertices: ");
11 scanf("%d", &n);
12 printf("\n\n\tEnter 1 if Edge exist else Enter 0:\n");
13 for(i=1; i<=n; i++)
14 for(j=1; j<=n; j++)
15 {
16 printf("\n\t\t\t\t adj[%d][%d]: ", i, j);
17 scanf("%d", &adj[i][j]);
18 }
19 TopologicalSort();
20 for(i=1;i<=n;i++)
21 if(Reach[i]!=1) break;
22 if(i>n)
23 {
24 printf("\n\n\tTopological Order is:\n\n\t\t");
25 for(i=1;i<m;i++)
26 printf("\t%d",order[i]);
27 }
28 else
29 printf("\n\n\tSorry Topological Order does not exist........");
30 }
31
32 void TopologicalSort()
33 {
34 int i,j,k,x;
35 for(x=1;x<=n;x++)
36 {
37 for(i=1;i<=n;i++)
38 {
39 for(j=1;j<=n;j++)
40 if(adj[j][i]==1) break;
41 if(j>n&&Reach[i]!=1)
42 {
43 for(k=1;k<=n;k++)
44 adj[i][k]=0;
45 Reach[i]=1;
46 order[m++]=i;
47 }
48 }
49 }
50 }

Explanation of Program:
 Line 1 includes header file that support standard functions in C language.
 Line 2 is prototype for function TopologicalSort().
 Line 11 reads the number of vertices.
 Line 19 calls the function TopologicalSort().
 Lines 32 to 50 perform Topological Sort by repeatedly identifying the remaining digraph a source,
which is a vertex with no incoming edges, and delete it along with all the edges outgoing from it.
The order in which the vertices are deleted yields a solution to the topological sorting problem..

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 70


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Insertion Sort

1 #include<stdio.h>
2 int main()
3 {
4 int i, j, n, temp, a[20];
5 printf("Enter total elements: ");
6 scanf("%d", &n);
7 printf("Enter %d elements: ",n);
8 for(i=0;i<n;i++)
9 scanf("%d",&a[i]);
10 for(i=1;i<n;i++)
11 {
12 temp=a[i];
13 j=i-1;
14 while((temp<a[j])&&(j>=0))
15 {
16 a[j+1]=a[j];
17 j=j-1;
18 }
19 a[j+1]=temp;
20 }
21 printf("After sorting: ");
22 for(i=0;i<n;i++)
23 printf(" %d",a[i]);
24 return 0;
25 }

Explanation of Program:
 Line 1 includes header file that support standard functions in C language.
 Line 4 is for variable declaration.
 Line 6 reads the value of n.
 Line 8-9 reads the array elements.
 Lines 10-20 perform Insertion Sort.
 Lines 22-23, display the sorted array elements.

3.4 Expected Results

Topological ordering of vertices in a given digraph.

reva@reva1:~/Desktop/ada_manual$ vi pgm09a.c
reva@reva1:~/Desktop/ada_manual$ cc pgm09a.c
reva@reva1:~/Desktop/ada_manual$ ./a.out
Enter how many vertices: 4

Enter 1 if Edge exist else Enter 0:

adj[1][1]: 0
adj[2][1]: 0
adj[3][1]: 0
adj[4][1]: 0

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 71


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

adj[1][2]: 1
adj[2][2]: 0
adj[3][2]: 0
adj[4][2]: 0

adj[1][3]: 1
adj[2][3]: 0
adj[3][3]: 0
adj[4][3]: 0

adj[1][4]: 0
adj[2][4]: 1
adj[3][4]: 1
adj[4][4]: 0

Topological Order is:

1 2 3 4
Insertion Sort

reva@reva1:~/Desktop/ada_manual$ vi pgm09b.c
reva@reva1:~/Desktop/ada_manual$ cc pgm09b.c
reva@reva1:~/Desktop/ada_manual$ ./a.out
Enter total elements: 5
Enter 5 elements:
50
30
40
10
20

After sorting: 10 20 30 40 50

3.5 Implementation Phase: Compile the Program and note the syntax errors/warning if occurred
during each compilation. Remove those syntax errors/warnings for generation of executable file.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 72


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

3.6 Simulation of Errors/Warnings:


3.6.1 Syntax Errors/Warnings:
S. No. Errors/Warnings Reflection of the Errors/Warnings in compilation/output
Simulated

3.6.2 Logical Errors:


S. No. Error Simulated Reflection of the error in compilation/output

4 Final Program and Results

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 73


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Actual Output Obtained

5 Assignment

5.1 Design a Program to Sort a set of elements in descending order by modifying the above
Insertion Sort algorithm
5.1.1 Algorithm

5.1.2 Coding in C Language

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 74


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

5.1.3 Actual Output Obtained

5.1.4 Implementation Phase: Compile the Program and note the syntax errors/warnings occurring
during each compilation. Remove the syntax errors/warnings for generation of executable file.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 75


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Viva Questions

1. What is the worst case complexity for insertion sort algorithm?

2. What is the output of insertion sort after the 1st iteration given the following sequence of
numbers: 73519846

3. In an insertion sort of n elements, how many times is the swap function called in the complete
execution of the algorithm?

4. How does insertion sort works?

5. What is the best case complexity for insertion sort algorithm?

6. What are the applications of topological sorting?

Program 10
1 Problem Statement
SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 76
DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

a. Check whether a given graph is connected or not using DFS method.


b. Print all the nodes reachable from a given starting node in a digraph using BFS method.

2 Student Learning Outcomes

After successful completion of this session, the student will able to:
 Describe the basic mechanics of BFS and DFS algorithms.
 Apply BFS and DFS to traverse a graph.

3 Design
3.1 Theory

DEPTH-FIRST SEARCH (DFS)

 Depth-first search starts a graph’s traversal at an arbitrary vertex by marking it as visited. On each
iteration, the algorithm proceeds to an unvisited vertex that is adjacent to the one it is currently in.
This process continues until a dead end —a vertex with no adjacent unvisited vertices is encountered.
 At a dead end, the algorithm backs up one edge to the vertex it came from and tries to continue
visiting unvisited vertices from there. The algorithm eventually halts after backing up to the starting
vertex, with the latter being a dead end. By then, all the vertices in the same connected component as
the starting vertex have been visited. If unvisited vertices still remain, the depth-first search must be
restarted at any one of them.
 It is convenient to use a stack to trace the operation of depth-first search. It is also very useful to
accompany a depth-first search traversal by constructing the depth-first search forest. The starting
vertex of the traversal serves as the root of the first tree in such a forest. Whenever a new unvisited
vertex is reached for the first time, it is attached as a child to the vertex from which it is being
reached. Such an edge is called a tree edge because the set of all such edges forms a forest. The
algorithm may also encounter an edge leading to a previously visited vertex other than its immediate
predecessor (i.e., its parent in the tree). Such an edge is called a back edge.
 Below figure shows the example for DFS.

Fig. Example for DFS


BREADTH-FIRST SEARCH (BFS)
 It proceeds in a concentric manner by visiting first all the vertices that are adjacent to a starting
vertex, then all unvisited vertices two edges apart from it, and so on, until all the vertices in the same
connected component as the starting vertex are visited. If there still remain unvisited vertices, the
algorithm has to be restarted at an arbitrary vertex of another connected component of the graph.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 77


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

 It is convenient to use a queue.


 It is useful to accompany a BFS traversal by constructing the so-called breadth-first search forest.
The traversal’s starting vertex serves as the root of the first tree in such a forest.
 Whenever a new unvisited vertex is reached for the first time, the vertex is attached as a child to the
vertex it is being reached from with an edge called a tree edge.
 If an edge leading to a previously visited vertex other than its immediate predecessor (i.e., its parent
in the tree) is encountered, the edge is noted as a cross edge.
 Below figure shows the example for BFS

BFS traversal queue: a, b e f, g, c h, d


Level: 1, 2 2 2, 3, 4 4, 5

Fig. Example for BFS

3.2 Algorithm

DFS method.
DFS(G)
//Implements a depth-first search traversal of a given graph
//Input: Graph G = (V, E)
//Output: Graph G with its vertices marked with consecutive integers
// in the order they are first encountered by the DFS traversal
1. mark each vertex in V with 0 as a mark of being “unvisited”
2. count ←0
3. for each vertex v in V do
4. if v is marked with 0
5. dfs(v).

Explanation of Algorithm:
 Line 1, mark each vertex in V with 0 as a mark of being “unvisited”.
 Line 2, initialize count to 0.
 Lines 3-5, for each vertex v in V, if v is marked with 0 call the function dfs(v).

dfs(v)
//visits recursively all the unvisited vertices connected to vertex v
//by a path and numbers them in the order they are encountered
//via global variable
1. count count ← count + 1; mark v with count
2. for each vertex w in V adjacent to v do
3. if w is marked with 0
4. dfs(w).

Explanation of Algorithm:

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 78


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

 Line 1, increment the count value by 1 and mark v with count.


 Lines 2-4, for each vertex w in V adjacent to v, if w is marked with 0 call the function dfs(w).

BFS method.

BFS(G)
//Implements a breadth-first search traversal of a given graph
//Input: Graph G = ( V, E)
//Output: Graph G with its vertices marked with consecutive integers
// in the order they are visited by the BFS traversal
1. mark each vertex in V with 0 as a mark of being “unvisited”
2. count ←0
3. for each vertex v in V do
4. if v is marked with 0
5. bfs(v).

Explanation of Algorithm:
 Line 1, mark each vertex in V with 0 as a mark of being “unvisited”.
 Line 2, initialize count to 0.
 Lines 3-5, for each vertex v in V, if v is marked with 0 call the function bfs(v).

bfs(v)
//visits all the unvisited vertices connected to vertex v
//by a path and numbers them in the order they are visited
//via global variable
1. count count ← count + 1;mark v with count and initialize a queue with v
2. while the queue is not empty do
3. for each vertex w in V adjacent to the front vertex do
4. if w is marked with 0
5. count ← count + 1;
6. mark w with count
7. add w to the queue
8. remove the front vertex from the queue.

Explanation of Algorithm:
 Line 1, increment the count value by 1 and mark v with count and initialize a queue with v.
 Lines 2-7, while the queue is not empty, for each vertex w in V adjacent to the front vertex, if w is
marked with 0, increment the count value by 1, mark w with count and add w to the queue.
 Line 8, remove the front vertex from the queue.

3.3 Coding using C Language

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 79


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

DFS method

1 #include<stdio.h>
2 int i, j, v, n;
3 int cost[9][9], visited[9],order[12];
4 void dfs(int v)
5 {
6 int w;
7 visited[v]=1;
8 for(w=1;w<=n;w++)
9 {
10 if(cost[v][w]&&(visited[w]==0))
11 {
12 visited[w]=1;
13 printf("%d\t ",w);
14 dfs(w);
15 }
16 }
17 }
18
19 main()
20 {
21 int flag=0;
22 printf( "The no of vertices=\t");
23 scanf("%d",&n);
24 printf("The adjacency matrix=\t");
25 for( i=1;i<=n;i++)
26 for( j=1;j<=n;j++)
27 {
28 scanf("%d",&cost[i][j]);
29 }
30
31 for(i=1;i<=n;i++)
32 visited[i]=0;
33
34 printf("\n\n\tThe starting vertex is \t");
35 scanf("%d",&v);
36 dfs(v);
37
38 for(i=1;i<=n;i++)
39 if(visited[i]==1)
40 {
41 flag=1;
42 }
43 else
44 {
45 flag=0;
46 break;
47 }
48
49 if(flag==1)
50 printf("graph is connected\n");

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 80


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

51 else
52 printf("graph is disconnected graph\n");
53 }

Explanation of Program:
 Line 1 includes header file that support standard functions in C language.
 Lines 2 and 3 are for variable declaration.
 Lines 4 to 17 perform DFS.
 Line 23 reads the value of n.
 Line 36 calls the function dfs(v).

7. BFS method.

1 # include<stdio.h>
2 void bfs(int a[20][20], int n, int source, int s[])
3 {
4 int i,f,r,q[20],u,v;
5 for(i=1; i<=n; i++)
6 s[i]=0;
7 f=r=0;
8 q[r]=source;
9 s[source]=1;
10 while(f<=r)
11 {
12 u=q[f++];
13 for(v=1; v<=n; v++)
14 {
15 if(a[u][v]==1 && s[v]==0)
16 {
17 s[v]=1;
18 q[++r]=v;
19 }
20 }
21 }
22 }
23 void main()
24 {
25 int n,a[20][20],source,s[20],i,j;
26 printf("Enter No. of Nodes: ");
27 scanf("%d",&n);
28 printf("Enter The Adjacency Matrix: \n");
29 for(i=1; i<=n; i++)
30 {
31 for(j=1; j<=n; j++)
32 {
33 scanf("%d",&a[i][j]);
34 }
35 }
36 printf("Enter The Source: ");
37 scanf("%d",&source);
38 bfs(a,n,source,s);

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 81


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

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


40 {
41 if(s[i]==0)
42 printf("Vertex %d is Not Reachable\n",i);
43 else
44 printf("Vertex %d is Reachable\n",i);
45 }
46 }

Explanation of Program:
 Line 1 includes header file that support standard functions in C language.
 Lines 4 and 25 are for variable declaration.
 Lines 2 to 22 perform BFS.
 Line 27 reads the value of n.
 Line 37 reads the value of source.
 Line 38 calls the function bfs(a,n,source,s).

3.4 Expected Results

DFS method.

reva@reva1:~/Desktop/ada_manual$./a.out

The no of vertices= 4

The adjacency matrix=

0110

0001

0001

1000

The starting vertex is 1

2 4 3 graph is connected

reva@reva1:~/Desktop/ada_manual$ ./a.out

The no of vertices= 4

The adjacency matrix=

0000

0001

0100

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 82


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

1000

The starting vertex is 1

graph is disconnected graph


8. BFS method.
Enter No. of Nodes: 4
Enter The Adjacency Matrix:

0110
0001
0001
1000

Enter The Source: 4


Vertex 1 is Reachable
Vertex 2 is Reachable
Vertex 3 is Reachable

Vertex 4 is Reachable

3.5 Implementation Phase: Compile the Program and note the syntax errors/warning if occurred
during each compilation. Remove those syntax errors/warnings for generation of executable
file.

3.6 Simulation of Errors/Warnings:


3.6.1 Syntax Errors/Warnings:

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 83


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

S. No. Errors/Warnings Reflection of the Errors/Warnings in compilation/output


Simulated

3.6.2 Logical Errors:


S. No. Error Simulated Reflection of the error in compilation/output

4 Final Program and Results

Actual Output Obtained


SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 84
DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

5 Assignment

5.1 Design of the Program Modify DFS to find Topological Sorting of a graph.
5.1.1 Algorithm

5.1.2 Coding in C Language

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 85


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

5.1.3 Actual Output Obtained

5.1.4 Implementation Phase: Compile the Program and note the syntax errors/warnings occurring
during each compilation. Remove the syntax errors/warnings for generation of executable
file.

Viva Questions

1) What is an adjacency matrix?

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 86


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

2) What is a weighted and un-weighted graph?

3) What is the relation between number of edges and no of odd and even vertices in a graph?

4) What are the applications of DFS and BFS?

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 87


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Program 11
1 Problem Statement

a. Implement Horspool algorithm for String Matching and find the number of key comparisons in
successful search and unsuccessful search.
b. Sort a given set of elements in ascending order which has duplicate entries. Use the sorting by
counting algorithm.

2 Student Learning Outcomes

After successful completion of this session, the student will able to:
 Understand / implement Horspool and sorting by counting algorithms.
 Design algorithms with strings as input and string handling functions.

3 Design
3.1 Theory

Horspool Algorithm:

Step 1 For a given pattern of length m and the alphabet used in both the pattern and text, construct the
shift table as described above.
Step 2 Align the pattern against the beginning of the text.
Step 3 Repeat the following until either a matching substring is found or the pattern reaches beyond the
last character of the text. Starting with the last character in the pattern, compare the corresponding
characters in the pattern and text until either all m characters are matched (then stop) or a mismatching
pair is encountered. In the latter case, retrieve the entry t (c) from the c’s column of the shift table where
c is the text’s character currently aligned against the last character of the pattern, and shift the pattern by
t (c) characters to the right along the text.

Distribution Counting:

The elements of A whose values are equal to the lowest possible value l are copied into the first F[0]
elements of S, i.e., positions 0 through F[0]− 1; the elements of value l + 1 are copied to positions from
F[0] to ( F[0]+ F[1] ) − 1; and so on. Since such accumulated sums of frequencies are called a
distribution in statistics, the method itself is known as distribution counting.

3.2 Algorithm

Horspool algorithm.
ALGORITHM ShiftTable(P [0 ..m − 1] )
//Fills the shift table used by Horspool’s and Boyer-Moore algorithms
//Input: Pattern P[0 ..m − 1] and an alphabet of possible characters
//Output: Table[0 ..size − 1] indexed by the alphabet’s characters and
//filled with shift sizes computed by formula

1. for i ←0 to size − 1 do
2. Table[ i]← m
3. for j ←0 to m − 2 do
4. Table[ P[ j ]]← m − 1− j

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 88


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

5 return Table.

Explanation of Algorithm:
 Lines 1-2, initialize all the elements of an array Table[] to m.
 Lines 3-4, compute the shift sizes.

ALGORITHM HorspoolMatching(P [0 ..m − 1] , T [0 ..n − 1] )


//Implements Horspool’s algorithm for string matching
//Input: Pattern P[0 ..m − 1] and text T [0 ..n − 1]
//Output: The index of the left end of the first matching substring
//or −1 if there are no matches
1. ShiftTable(P [0 ..m − 1] ) //generate Table of shifts
2. i ← m − 1 //position of the pattern’s right end
3. while i ≤ n − 1 do
4. k←0 //number of matched characters
5. while k ≤ m − 1 and P[ m − 1− k]= T [ i − k] do k← k + 1
6. if k = m
7. return i − m + 1
8. else i ← i + Table[ T [ i]]
9. return −1.

Explanation of Algorithm:
 Lines 1, calls the function ShiftTable(P [0 ..m − 1] ) to generate Table of shifts.
 Lines 2, set I value as the position of the pattern’s right end.
 Line 4, initially number of matched characters is 0.
 Line 6-7 if k=m return i − m + 1.

Sorting by counting algorithm.

DistributionCountingSort(A[0 ..n − 1] , l, u)
//Sorts an array of integers from a limited range by distribution counting //Input: An array A[0 ..n − 1] of
integers between l and u (l ≤ u)
//Output: Array S[0 ..n − 1] of A’s elements sorted in nondecreasing order

1. for j ←0 to u − l do D[ j ]←0
2. for i ←0 to n − 1 do D[ A[ i]− l]← D[ A[ i]− l]+ 1
3. for j ←1 to u − l do D[ j ]← D[ j − 1]+ D[ j ]
//reuse for distribution for i ← n − 1 down to 0 do j ← A[ i]− l
4. S[ D[ j ]− 1]← A[ i]
5. D[ j ]← D[ j ]− 1
6. return S.

Explanation of Algorithm:
 Line 1, initialize the frequencies of elements.
 Line 2, compute the frequencies.
 Line 3, distribution for i ← n − 1 down to 0 do j ← A[ i]− l
 Line 4, assign A[ i] to S[ D[ j ]− 1].
 Line 5, assign D[ j ]− 1 to D[ j ].
3.3 Coding using C Language

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 89


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Horspool algorithm.

1 #include<stdio.h>
2 #include<string.h>
3 #define MAX 500
4 int t[MAX];
5
6 void shifttable(char p[])
7 {
8 int i,j,m;
9 m=strlen(p);
10 for(i=0;i<MAX;i++)
11 t[i]=m;
12 for(j=0;j<m-1;j++)
13 t[p[j]]=m-1-j;
14 }
15
16 int horspool(char src[],char p[])
17{
18 int i,j,k,m,n;
19 n=strlen(src);
20 m=strlen(p);
21 printf("\nLength of text=%d",n);
22 printf("\n Length of pattern=%d",m);
23 i=m-1;
24 while(i<n)
25 {
26 k=0;
27 while((k<m)&&(p[m-1-k]==src[i-k]))
28 k++;
29 if(k==m)
30 return(i-m+1);
31 else
32 i+=t[src[i]];
33 }
34 return -1;
35 }
36
37 void main()
38 {
39 char src[100],p[100];
40 int pos;
41 printf("Enter the text in which pattern is to be searched:\n");
42 gets(src);
43 printf("Enter the pattern to be searched:\n");
44 gets(p);
45 shifttable(p);

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 90


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

46 pos=horspool(src,p);
47 if(pos>=0)
48 printf("\n The desired pattern was found starting from position %d",pos+1);
49 else
50 printf("\n The pattern was not found in the given text\n");
51 }

Explanation of Program:
 Lines 1 and 2 includes header file that support standard functions in C language.
 Lines 16 to 35 search pattern in a string using Horspool’s Algorithm..

Sorting by counting algorithm.


1 #include <stdio.h>
2 void counting_sort(int A[], int k, int n)
3 {
4 int i, j;
5 int B[15], C[100];
6 for (i = 0; i <= k; i++)
7 C[i] = 0;
8 for (j = 1; j <= n; j++)
9 C[A[j]] = C[A[j]] + 1;
10 for (i = 1; i <= k; i++)
11 C[i] = C[i] + C[i-1];
12 for (j = n; j >= 1; j--)
13 {
14 B[C[A[j]]] = A[j];
15 C[A[j]] = C[A[j]] - 1;
16 }
17 printf("The Sorted array is : ");
18 for (i = 1; i <= n; i++)
19 printf("%d ", B[i]);
20 }
21 int main()
22 {
23 int n, k = 0, A[15], i;
24 printf("Enter the number of input : ");
25 scanf("%d", &n);
26 printf("\nEnter the elements to be sorted :\n");
27 for (i = 1; i <= n; i++)
28 {
29 scanf("%d", &A[i]);
30 if (A[i] > k) {
31 k = A[i];
32 }
33 }
34 counting_sort(A, k, n);
35 printf("\n");

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 91


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

36 return 0;
37 }

Explanation of Program:
 Line 1 includes header file that support standard functions in C language.
 Lines 2 to 23 perform sorting by counting.

3.4 Expected Results

Horspool algorithm.

reva@reva1:~/Desktop/ada_manual$ vi pgm11a.c
reva@reva1:~/Desktop/ada_manual$ cc pgm11a.c
reva@reva1:~/Desktop/ada_manual$ ./a.out
Enter the text in which pattern is to be searched:
god is great
Enter the pattern to be searched:
great

Length of text=12

Length of pattern=5

The desired pattern was found starting from position 8

Sorting by counting algorithm.


reva@reva1:~/Desktop/ada_manual$ /a.out

Enter the number of input : 10

Enter the elements to be sorted :

21 4 18 15 24 6 9 1 5 4

The Sorted array is : 1 4 4 5 6 9 15 18 21 24

3.5 Implementation Phase: Compile the Program and note the syntax errors/warning if occurred
during each compilation. Remove those syntax errors/warnings for generation of executable file.

3.6 Simulation of Errors/Warnings:

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 92


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

3.6.1 Syntax Errors/Warnings:


S. No. Errors/Warnings Reflection of the Errors/Warnings in compilation/output
Simulated

3.6.2 Logical Errors:


S. No. Error Simulated Reflection of the error in compilation/output

4 Final Program and Results

Actual Output Obtained

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 93


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

5 Assignment

Sort a given set of elements in ascending order using comparison counting algorithm.
5.1 Design of the Program
5.1.1 Algorithm

5.1.2 Coding in C Language

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 94


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

5.1.3 Actual Output Obtained

5.1.4 Implementation Phase: Compile the Program and note the syntax errors/warnings occurring
during each compilation. Remove the syntax errors/warnings for generation of executable file.

Viva Questions

1) Will the comparison counting algorithm work correctly for arrays with equal values?

2) Assuming that the set of possible list values is {a, b, c, d}, sort the following list in alphabetical
order by distribution counting algorithm:
i. b, c, d, c, b, a, a, b

3) Is the distribution counting algorithm stable?

Program 12
1 Problem Statement

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 95


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

a. Implement N Queen's problem using Back Tracking.


b. Find a subset of a given set S = {sl, s2, ....., sn} of n positive integers whose sum is equal to a given
positive integer d.

2 Student Learning Outcomes


After successful completion of this session, the student will able to:
 Explain basic concepts of backtracking algorithm
 Understand that heuristic optimization strategies must be used when no good exact algorithm is
known.
3 Design
3.1 Theory

N-Oueens Problem
The problem is to place n queens on an n-by-n chessboard so that no two queens attack each other by
being in the same row or in the same column or on the same diagonal. For n = 1, the problem has a trivial
solution, and it is easy to see that there is no solution for n = 2 and n = 3. So let us consider the four-
queens problem and solve it by the backtracking technique. Since each of the four queens has to be placed
in its own row, all we need to do is to assign a column for each queen on the board presented below We
start with the empty board and then place queen 1 in the first possible position of its row, which is in
column 1 of row 1. Then we place queen 2, after trying unsuccessfully columns 1 and 2, in the first
acceptable position for it, which is square (2,3), the square in row 2 and column 3. This proves to be a
dead end because there is no acceptable position for queen 3. So, the algorithm backtracks and puts queen
2 in the next possible position at (2,4). Then queen 3 is placed at (3,2), which proves to be another dead
end. The algorithm then backtracks all the way to queen 1 and moves it to (1,2). Queen 2 then goes to
(2,4), queen 3 to (3,1), and queen 4 to ( 4,3), which is a solution to the problem.

Subset sum Problem


Subset sum problem is to find subset of elements that are selected from a given set whose sum adds up to
a given number K. We are considering the set contains non-negative values. It is assumed that the input
set is unique (no duplicates are presented).
3.2 Algorithm
AlGORITHM: NQueens
1 Start in the leftmost column
2 If all queens are placed return true
3 Try all rows in the current column. Do following for every tried row.
a) If the queen can be placed safely in this row then mark this [row, column] as part of the solution and
recursively check if placing queen here leads to a solution.
b) If placing queen in [row, column] leads to a solution then return true.
c) If placing queen doesn't lead to a solution then umark this [row, column] (Backtrack) and go to step
(a) to try other rows.
4 If all rows have been tried and nothing worked, return false to trigger backtracking.

ALGORITHM Subsetsum(A [0 ..n − 1], b)


//Implements Subsetsum algorithm
//Input: A[0 ..n − 1] and b

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 96


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

//Output: Subsets of elements that are selected from a given set whose sum adds up to a given number b.
1 for k = 1 to n do
2 for i = b to 0
3 if A[i] = 1 and ak + i < b then
4 A[ak + i] := 1
5 if A[b] = 1 then some subset adds up to b

Explanation of Algorithm:
 Lines 1-5, for k = 1 to n, for i = b to 0, Subsets of elements are selected from a given set based on
the condition A[b] = 1 whose sum adds up to a given number b.

3.3 Coding using C Language

N Queen's problem

1 #include<stdio.h>
2 #include<stdlib.h>
3 const int max=20;
4 int place(int x[],int k)
5 {
6 int i;
7 for(i=0;i<k;i++)
8 if (x[i]==x[k] || abs(x[i]-x[k])==abs(i-k))
9 return 0;
10 return 1;
11
12 }
13
14 void display(int x[], int n)
15 {
16 char chessb[max][max];
17 int i,j;
18 for(i=0;i<n;i++)
19 for(j=0;j<n;j++)
20 chessb[i][j]='x';
21 for(i=0;i<n;i++)
22 chessb[i][x[i]]='q';
23
24 for(i=0;i<n;i++)
25 {
26
27 for(j=0;j<n;j++)
28 printf("%c", chessb[i][j]);
29
30 printf ("\n");
31 }
32
33 printf ("\n");
34
35 }
36

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 97


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

37 void nqueens(int n)
38 {
39 int x[max];
40 int k;
41 x[0]=-1;
42 k=0;
43 while(k>=0)
44 {
45 x[k]=x[k]+1;
46 while(x[k]<n && !place(x,k))
47 x[k]=x[k]+1;
48 if(x[k]<n)
49 if (k==n-1)
50 display(x,n);
51 else
52 {
53 k++;
54 x[k]=-1;
55 }
56 else
57 k--;
58 }
59 }
60
61 main()
62 {
63 int n;
64 printf("enter the no of queens\n");
65 scanf("%d", &n);
66 printf("the soln to %d queens problem is \n", n);
67 nqueens(n);
68 }

Explanation of Program:
 Lines 1 and 2 include header file that support standard functions in C language.
 Lines 4 to 12 place the queens.
 Lines 37 to 59 solve n-queens problem.
 Line 65, reads the value of n.
 Line 67, calls the function nqueens(n).

Subset sum Problem

1 #include<stdio.h>
2 main()
3 {
4 int set[25],m,n,i,j,k,d,sum,flag=0;
5 printf("\n\tSize of the set:");
6 scanf("%d",&n);
7 printf("\n\tElements of the set:");
8 for(i=1;i<=n;i++)
9 scanf("%d",&set[i]);
10 printf("\tSubset d value:");

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 98


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

11 scanf("%d",&d);
12 for(i=1;i<=n;i++)
13 {
14
15 if(set[i]==d)
16 {
17 printf("%d\n",set[i]);
18 flag=1;
19 continue;
20 }
21 for(j=i+1;j<=n;j++)
22 {
23 sum=set[i]+set[j];
24 if(sum==d)
25 {
26 printf("%d\t",set[i]);
27 printf("%d\n",set[j]);
28 flag=1;
29 }
30 else
31 {
32 for(k=j+1;k<=n;k++)
33 {
34 if(sum+set[k]==d)
35 {
36 printf("%d\t", set[i]);
37 printf("%d\t", set[j]);
38 printf("%d\n", set[k]);
39 flag=1;
40 break;
41 }
42 }
43
44 }
45
46 }
47
48 }
49
50 if(!flag)
51 printf("no solution");
52 }

Explanation of Program:
 Line 1 includes header file that support standard functions in C language.
 Lines 2 to 52 solve subset sum problem.
 Line 6, reads the value of size of the set n.
 Lines 8-9, reads the array set[].
 Line 11, reads the value of d.
 Lines 21-46 displays the subset.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 99


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

3.4 Expected Results

N Queen's problem using Back Tracking.

reva@reva1:~/Desktop/ada_manual$ cc pgm12a.c
reva@reva1:~/Desktop/ada_manual$ ./a.out
enter the no of queens
4

the soln to 4 queens problem is

xqxx
xxxq
qxxx
xxqx

xxqx
qxxx
xxxq
xqxx

Subset sum Problem


Size of the set

Elements of the set:

2 3 6 7 8

Subset value:

10

2 8

3 7

3.5 Implementation Phase: Compile the Program and note the syntax errors/warning if occurred
during each compilation. Remove those syntax errors/warnings for generation of executable file.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 100


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

3.6 Simulation of Errors/Warnings:


3.6.1 Syntax Errors/Warnings:
S. No. Errors/Warnings Reflection of the Errors/Warnings in compilation/output
Simulated

3.6.2 Logical Errors:


S. No. Error Simulated Reflection of the error in compilation/output

4 Final Program and Results

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 101


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Actual Output Obtained

5 Assignment

5.1 Design of the Program : Hamiltonian Circuit problem


5.1.1 Algorithm

5.1.2 Coding in C Language

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 102


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

5.1.3 Actual Output Obtained

5.1.4 Implementation Phase: Compile the Program and note the syntax errors/warnings occurring
during each compilation. Remove the syntax errors/warnings for generation of executable file.

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 103


DESIGN AND ANALYSIS OF ALGORITHMS REVA UNIVERSITY

Viva Questions

1) What is backtracking?

2) How does n-queens algorithm work?

3) Apply Backtracking to the travelling salesman problem for a problem instance and construct
state space tree

SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY 104

You might also like