DAA Lab Manual
DAA Lab Manual
FOURTH SEMESTER
CSE_2261
LABORATORY MANUAL
CONTENTS
LAB PAGE
TITLE REMARKS
NO. NO.
10 DYNAMIC PROGRAMMING 42
11 GREEDY TECHNIQUE 45
ii
Course Objectives
To write programs for solving various problems with different algorithm design techniques and
data structures
• To measure the complexities involved in an algorithm or the resulting program
• To make a decision regarding the right algorithm or the resulting program for
an environment involving the nature of input, configuration of computational
device and/or any other conditions.
Course Outcomes
At the end of this course, students will have the
• Ability to design one or more algorithms for a problem using appropriate data
structures
• Convert the algorithm into a program which is efficient
• Ability to determine the complexity of various algorithms or the resulting
program
Evaluation Plan
• Internal Assessment Marks : 60 marks
iii
INSTRUCTIONS TO THE STUDENTS
Pre- Lab Session Instructions
1. Students should carry the Lab Manual Book and the required stationery to every
lab session
2. Be in time and follow the institution dress code
3. Must Sign in the log register provided
4. Make sure to occupy the allotted seat and answer the attendance
5. Adhere to the rules and maintain the decorum
ii
o Lab exercises - to be completed during lab hours
o Additional Exercises - to be completed outside the lab or in the lab to
enhance the skill
• In case a student misses a lab class, he/ she must ensure that the experiment is
completed during the repetition lab with the permission of the faculty concerned.
• Questions for lab tests and examination are not necessarily limited to the questions
in the manual, but may involve some variations and / or combinations of the
questions.
• A sample note preparation is given as a model for observation.
• You may write scripts/programs to automate the experimental analysis of
algorithms and compare with the theoretical result.
• You may use spreadsheets to plot the graph.
iii
Lab No:1
Objectives:
Description: Data Structures specify the structure of data storage in a program. Various
data structures namely arrays, stacks, queues, linked lists, trees are used for storing
data. Each data structure is different from the other in its fundamental way of storing. In
arrays, a contiguous piece of memory is allocated for storing data. Static and Dynamic
arrays are two types of array which differ by the instance at which memory is allocated.
In static arrays, memory is allocated at compile time of the program whereas in
Dynamic arrays memory is allocated at run time. Dynamic arrays overcome the
problem of unnecessary wastage of memory space. Stack is a data structure in which the
insertion to the Stack (called as push) and removal from the stack (called as pop)
operations are performed in Last In First Out (LIFO) order. LIFO specifies that the last
item to be pushed is the first one to be popped. Queue is a data structure in which the
insertion to the queue (enque) and removal of element from the queue (Dequeue) happen
in the same order. This means it follows First In First Out (FIFO) order. Linked lists store
data in non-linea manner. A node of a linked list is created at run time and is used to
store data element. Nodes of a linked list will be allocated memory at run time and the
nodes can be anywhere in memory. Singly linked list and doubly linked lists are two
broad types of linked lists. Single linked list has a single pointer to the next node
whereas doubly linked list has two pointers one to the left node and other to the right
node. A special value NULL will be used to denote the non-existence of node. Trees are
very useful in specific storage requirements of graphs, dictionaries etc. Binary tree is a
special form of trees in which every node can have maximum two children.
I. SOLVED EXERCISE:
1) Write an algorithm and program to implement a doubly linked list which supports
the following operations
i. Create the list by adding each node at the front.
ii. Insert a new node to the left of the node whose key value is read as an input.
iii. Delete all occurrences of a given key, if it is found. Otherwise, display
appropriate message.
iv. Search a node based on its key value.
v. Display the contents of the list.
1
Lab No:1
Description : Doubly linked list is a data structure in which the data elements are stored
in nodes and the nodes are connected by two links. Out of two links one link points to
the neighboring node in the left direction and the other link to the node in the right
direction. Addresses of nodes will be used to represent the node. A special value NULL
is used to represent the absence of a node. Creating the doubly linked list, insertion of
an element to the left/right of any node, deletion of all nodes with specific node content
and displaying all nodes are the operations commonly performed on a doubly linked
list. Each of the operations consumes certain amount of time and memory. Hence they
differ in time and space efficiency.
2
Lab No:1
node->llink = newNode
head = newNode
end if
else
print “Unable to insert, node with value “ val “not found”
return
end if
end
deleteAll(int delVal)
begin
node = head
while node != NULL
if node->val == delVal
if node->llink != NULL then
node -> llink ->rlink = node -> rlink
if node->rlink != NULL then
node->rlink->llink = node->llink
node = node->rlink
else
node->llink->rlink = NULL
node=NULL
end if
else
if node->rlink != NULL then
node ->rlink->llink = NULL
head = node->rlink
node = head
release memory for node
else
head = node = NULL
release memory for node
end if
end if
else
node = node->rlink
end if
end while
end
3
Lab No:1
searchNode(int searchVal)
begin
node=head
while node != NULL
do
if node->val == searchVal then
print “Node is found with key “, searchVal
end if
node = node->rlink
end do
end
displayAll()
begin
node = head
while node != NULL
do
print “Node with val “, node->val
node = node->rlink
end do
end
Time Complexity:
For Insertion, Search, Delete, Display All operations the complexity is O(n) where n
is the number of nodes.
Program
#include<stdio.h>
#include<stdlib.h>
struct node {
int val;
struct node *llink,*rlink;
};
4
Lab No:1
}
void deleteAll(int delVal)
{
5
Lab No:1
NODE nd,nxtNode;
nd = head;
}
else {
if (nd->rlink != NULL) {
nd ->rlink->llink = NULL;
head = nd->rlink;
free(nd);
nd = head;
}
else {
free(nd);
head = nd = NULL;
}
}
}
else
nd = nd->rlink;
}
}
6
Lab No:1
nd=head;
while (nd != NULL) {
if (nd->val == searchVal)
printf( "Node is found with key %d\n", searchVal);
nd = nd->rlink;
}
}
void displayAll()
{
NODE nd;
nd = head;
while (nd != NULL) {
printf("Node with val %d\n", nd->val);
nd = nd->rlink;
}
}
int main() {
int choice, val,before;
do {
printf("1. Create List\n");
printf("2. Insert into List\n");
printf("3. Delete all by value\n");
printf("4. Search by value\n");
printf("5. Display all\n");
printf("6. Exit\n");
printf("Enter your choice :");
scanf("%d", &choice);
switch(choice) {
case 1: printf("Please enter the node value");
scanf("%d", &val);
CreateList(val);
break;
case 2: printf("Please enter the node value to insert ");
scanf("%d", &val);
printf("Please enter the node value before which new
node has to be inserted ");
scanf("%d", &before);
insertIntoList(before, val);
break;
case 3:printf("Enter the node value to be deleted ");
scanf("%d", &val);
7
Lab No: 2
deleteAll(val);
break;
case 4:printf("Enter the node value to be searched ");
scanf("%d", &val);
searchNode(val);
break;
case 5:displayAll();
break;
case 6:
break;
default:printf("Invalid choice ");
break;
}
}while(choice != 6);
return 0;
}
8
Lab No: 2
Enter the node value to be deleted 3
1. Create List
2. Insert into List
3. Delete all by value
4. Search by value
5. Display all
6. Exit
Enter your choice :4
Enter the node value to be searched 5
Node is found with key 5
1. Create List
2. Insert into List
3. Delete all by value
4. Search by value
5. Display all
6. Exit
Enter your choice :5
Node with val 5
1. Create List
2. Insert into List
3. Delete all by value
4. Search by value
5. Display all
6. Exit
Enter your choice :6
1). Write a program to construct a binary tree to support the following operations.
Assume no duplicate elements while constructing the tree.
i. Given a key, perform a search in the binary search tree. If the key is found
then display “key found” else insert the key in the binary search tree.
2). Write a program to implement the following graph representations and display
i. Adjacency list
ii. Adjacency matrix
1). Solve the problem given in solved exercise using singly linked list.
2). Write a program to implement Stack and Queue using circular doubly linked list.
3) Write a program to convert a Binary tree to a Doubly linked list
9
Lab No: 2
LAB NO: 2 Date:
I. SOLVED EXERCISE:
1) Write an algorithm for finding the Greatest Common Divisor (GCD) of two numbers
using Euclid’s algorithm and implement the same. Determine the time complexity of the
algorithm.
ALGORITHM EuclidGCD(m, n)
//Computes gcd(m, n) by Euclid’s algorithm
//Input: Two nonnegative, not-both-zero integers m and n
//Output: Greatest common divisor of m and n
while n ≠ 0 do
r ←m mod n
m←n
n←r
return m
10
Lab No: 2
Time Complexity: O(logn). The worst case for this algorithm is when the inputs are two
consecutive Fibonacci numbers. We can plot the graph of (m+n) vs the step count
(opcount is shown in the sample code), where m and n are the two inputs to function
EuclidGCD.
Program
#include<stdio.h>
unsigned int EuclidGCD(unsigned int m, unsigned int n) {
unsigned int r;
int opcount = 0; // variable to count how many times the basic operation executes.
while(n!=0) {
opcount++;
r = m %n;
m = n;
n=r;
}
printf(“Operation count= %d\n”, opcount);
return m;
}
int main() {
unsigned int m,n;
printf(“Enter the two numbers whose GCD has to be calculated“);
scanf(“%d”, &m);
scanf(“%d”, &n);
printf(“GCD of two numbers using Euclid’s method is %d”,
EuclidGCD(m,n)); return 0;
}
11
Lab No: 2
(m+n) vs opcount
25
20
15
opcount
10
0
0 5000 10000 15000 20000
(m+n)
1). Write a program to find GCD using consecutive integer checking method and
analyze its time efficiency.
2). Write a program to compute nth Fibonacci number recursively and analyze its
time efficiency
III. ADDITIONAL EXERCISES
1) Write a program to implement recursive solution to the Tower of Hanoi puzzle
and analyze its time efficiency.
2) Write a program to find GCD using middle school method and analyze its time
efficiency.
3) Write a program to delete strong numbers from an array using recursion [A strong
number is such that the sum of it's factorial is the number itself]
12
Lab No: 3
I. SOLVED EXERCISE:
1) Write a program to sort a set of integers using selection sort algorithm and analyze its
time efficiency. Obtain the experimental result of order of growth. Plot the result for the
best and worst case.
Description: In selection sort, we scan 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. This is repeated for all positions.
13
Lab No: 3
Time Complexity:
The worst case occurs when elements are given in decreasing order.
Cworst(n) = ∑n–2 𝑛 − 1 − 𝑖 − 1 + 1
= n-1 + n-2 … +1
= θ(n2)
This can be observed by repeating the experiment with the worst case inputs for
different array sizes say 10, 15, 20, 35, 100. A plot of number of elements in the array
vs opcount (opcount is shown in the sample code) gives a quadratic curve.
Program
#include<stdio.h>
#include<stdlib.h>
void selectionSort(int *a, unsigned int n)
{
unsigned int i,j,min;
int temp;
int opcount=0; // introduce opcount
for(i= 0;i<n-1;i++)
{
min=i;
for(j=i + 1;j<n;j++)
{
++opcount; // increment opcount for every comparison
if(a[j ]<a[min])
min=j;
}
//swap A[i] and A[min]
temp = a[i];
a[i] = a[min];
a[min]=temp;
}
printf("\nOperation Count %d\n",opcount);
}
14
Lab No: 3
int main() {
int *a;
int i,n = 5;
// generate worst case input of different input size
for (int j=0; j < 4; j++) // repeat experiment for 4 trials
{
a = (int *)malloc(sizeof(int)*n);
for (int k=0; k< n; k++)
a[k] = n-k; // descending order list
printf("Elements are ");
for(i=0;i<n;i++)
printf("%d ",a[i]);
selectionSort(a,n);
printf("Elements after selection sort ");
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
free(a);
n = n + 5; // try with a new input size
}
return 0;
}
15
Lab No: 3
200
150
0
0 5 10 15 20 25
-50
input size (n)
16
Lab No: 4
I. SOLVED EXERCISE:
1). Write a program to implement Knapsack problem using brute-force design technique
and analyze its time efficiency. Obtain the experimental result of order of growth and plot
the result. Knapsack Problem: Given n items of known weights w1, w2, ..wn values v1, v2,
...vn and a knapsack of capacity B, find the most valuable subset of items that fit into the
knapsack.
17
Lab No: 4
Time Complexity :
The basic operation in this is comparison inside loop. This is repeated as many times
as the iterations of the loop. The loop is repeated 2n times.
This can be observed by repeating the experiment for knapsack problems with number
of items as 3, 4, 5, 10, 20….. by randomly generating the weight set and the profit set.
A plot of number of items, n, vs opcount (opcount is shown in the sample code) gives
an exponential curve.
Program
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int Knapsack(unsigned int *w, unsigned int *v, unsigned int n, unsigned int B)
{
unsigned int i,temp;
unsigned int maxVal=0, maxSequence=0;
unsigned int totalWeight, totalValue;
int opcount=0; // Intialize the opcount variable
unsigned int index=0;
//Generate bit array
for(i=1;i<pow(2,n);i++)
{
++opcount; //increment opcount for every possible subsets
//Compute total weight
temp = i;
totalWeight=totalValue=0;
index=0;
while(temp) {
if(temp & 0x1) {
totalWeight = totalWeight + w[index];
totalValue = totalValue + v[index];
}
index++;
temp = temp >> 1;
}
if(totalWeight <= B && totalValue > maxVal) {
maxVal = totalValue;
maxSequence = i;
18
Lab No: 4
}
}
printf("\n Operation count = %d\n",opcount);
return maxSequence;
}
int main() {
unsigned int *v,*w, i,n,knaps, B;
printf("Enter the number of elements ");
scanf("%d", &n);
v= (unsigned int *)calloc(n, sizeof(unsigned int));
w = (unsigned int *) calloc(n, sizeof(unsigned int));
printf("Please enter the weights");
for(i=0;i<n;i++)
scanf("%d",&w[i]);
printf("Please enter the values");
for(i=0;i<n;i++)
scanf("%d",&v[i]);
printf("Please enter the Knapsack capacity");
scanf("%d", &B);
knaps = Knapsack(w,v,n,B);
printf("Knapsack contains the following items \n");
i=0;
while(knaps) {
if(knaps & 0X1)
printf("item %u value %u", (i+1), v[i]);
i++;
knaps = knaps >> 1;
}
return 0;
}
19
Lab No: 5
1). Write a program for assignment problem by brute-force technique and analyze its
time efficiency. Obtain the experimental result of order of growth and plot the
result.
2).Write a program to implement the Traveling Salesman Problem using Brute
Force Method
A graph is said to be bipartite if all its vertices can be partitioned into two
disjoint subsets X and Y so that every edge connects a vertex in X with a vertex
in Y.
2). Write a program to construct a graph for the following maze. One can model a
maze by having a vertex for a starting point, a finishing point, dead ends, and all
the points in the maze where more than one path can be taken, and then connecting
the vertices according to the paths in the maze. Also find the solution to the maze
using Depth-First-Search.
3). Write a program for depth-first search of a graph. Identify the push and pop order
of vertices.
20
Lab No: 5
LAB NO: 5 Date:
I. SOLVED EXERCISE:
1). Write a program to sort a set of numbers using insertion sort and analyze its time
efficiency. Obtain the experimental result of order of growth and plot the result.
Description: We assume that 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[1]... ≤A[n-2]
has already been solved to give us a sorted array of size n-1. The new element A[n-
1] need to be inserted into the right position. We compare each element starting
from A[n-2] down to A[0] to check the right position for A[n-1]. Once found, we
insert into that position.
21
Lab No: 5
Time Complexity :
The worst case occurs when elements are given in decreasing order.
In such cases, j will range from 0 to i-1.
Cworst(n) = ∑n–1 i − 1 − 1 + 1
= n-2 + n-3 … +0
= θ(n2)
This can be observed by repeating the experiment with the worst-case inputs for
different array sizes say 10, 15, 20, 35, 100. A plot of number of elements in the
array vs opcount (opcount is shown in the sample code) gives a quadratic curve.
Program :
#include<stdio.h>
#include<stdlib.h>
void insertionSort(int *a, unsigned int n)
{
int i, j, v;
int opcount=0;
for(i=1;i<n;i++)
{
v=a[i]
; j=i-
1;
// increment opcount whenever there is an element comparison
while(++opcount && j>=0 && a[j]> v)
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=v;
}
printf(“\n Operation count %d\n”,opcount);
}
int main() {
int *a;
int i,n = 5;
// generate worst case input of different input size
22
Lab No: 5
Tabulate the values of n and opcount as shown below and plot the graph.
23
Lab No: 5
250
150
100
Operation Count - c(n)
50
0
0 5 10 15 20 25
Input Size n
2). Write a program to find diameter of a binary tree. Diameter of a binary tree is
the longest path between any two nodes.
For e.g. consider the following two binary trees.
The diameter in each tree is 9. In the first one, longest path passes through root
whereas in the second it does not.
24
Lab No: 6
I. SOLVED EXERCISE:
1). Write a program to determine the height of a binary search tree and analyze its time
efficiency.
ALGORITHM Height(T )
//Computes recursively the height of a binary tree
//Input: A binary tree T
//Output: The height of T
if T = NULL then
return −1
else
return max{Height(Tleft ), Height(Tright)} + 1
end if
Time Complexity : The time complexity of this algorithm is 𝜃(n) considering the
basic operation as comparison (or addition). This can be observed by repeating the
experiment for trees with different number of nodes as 5, 7, 10, 12, 20….. A plot
of number of nodes, n, vs opcount (opcount is shown in the sample code) gives a
linear curve.
25
Lab No: 6
Program
#include<stdio.h>
#include<stdlib.h>
struct node{
int val;
struct node *left, *right;
};
NODE root=NULL;
26
Lab No: 6
27
Lab No: 6
1. Insert an element
2. Find Height of BST
3. Exit
Please enter your choice: 2
Height of BST : 2
1. Insert an element
2. Find Height of BST
3. Exit
Please enter your choice: 3
1) Write a program in C to find an where n > 0 using divide and conquer strategy.
2) Given an image, find the defective region in the image using divide and conquer
technique. The defective region is denoted by 0 and the non-defective region is
denoted by 1.
3) Find total number of nodes in a binary tree and analyze its efficiency. Obtain the
experimental result of order of growth and plot the result.
28
Lab No:7
Description: The technique is called as Transform and Conquer because these methods
work as two-stage procedures. First in the transformation stage, the problem’s instance is
modified to be, for one reason or another, more amenable to solution. Then in the second
or conquering stage it is solved.
There are three major variations of this idea that differ by what we transform a given
instance.
Transformation to a simpler or more convenient instance of the same problem-we
call it instance simplification.
Transforming to a different representation of the same instance-we call it
representation change.
Transformation to an instance of a different problem for which an algorithm is
already available-we call it problem reduction.
I. SOLVED EXERCISE:
1). Write a program to create a binary search tree and display its elements using all
the traversal methods and analyse its time efficiency.
Description: Binary search tree is a binary tree whose nodes contain elements of a set
of orderable items, one element per node, so that all elements in the left subtree are
smaller than the element in the subtree’s root, and all the elements in the right subtree
are greater than it. Note that this transformation from a set to a binary search tree is an
example of the representation-change technique.
To create and maintain the information stored in a binary search tree, we need an
operation that inserts new nodes into the tree. We use the following insertion approach.
A new node is always inserted into its appropriate position in the tree as a leaf. We write
a function that inserts an item into the tree, given a pointer to the root of the whole tree:
create(tree, item). We compare the item to the data of the (current) root node and then
call the function to insert the item into the correct subtree-the left subtree if item's key is
less than the key of the root node, and the right subtree if item's key is greater than the
key of the root node. The argument ‘tree’, to the create(), is a reference parameter. The
case where tree is NULL is the base case where a node will be created and the element
will be stored. The recursive call will pass the reference to the appropriate left or right
29
Lab No:7
subtree depending on the item to be inserted. The important point to remember is that
passing a pointer by value allows the function to change what the caller's pointer points
to; passing a pointer by reference allows the function to change the caller's pointer as
well as to change what the pointer points to.
Time Efficiency:
T(n)=O(n), where n is number of nodes
Program
#include<stdio.h>
typedef struct node
{
int info;
struct node *left,*right;
}NODE;
30
Lab No:7
}
return(bnode);
}
void inorder(NODE *ptr)
{
if(ptr!=NULL)
{
inorder(ptr->left);
printf("%5d",ptr->info);
inorder(ptr->right);
}
}
void postorder(NODE *ptr)
{
if(ptr!=NULL)
{
postorder(ptr->left);
postorder(ptr->right);
printf("%5d",ptr->info);
}
}
void preorder(NODE *ptr)
{
if(ptr!=NULL)
{
printf("%5d",ptr->info);
preorder(ptr->left);
preorder(ptr->right);
}
}
void main()
{
int n,x,ch,i;
NODE *root;
root=NULL;
while(1)
{
printf("********************Output********************\n\n");
printf(" Menu \n");
printf(" 1. Insert\n 2. All traversals\n 3. Exit\n");
printf("Enter your choice:");
scanf("%d",&ch);
31
Lab No:7
switch(ch)
{
case 1: printf("Enter node (do not enter duplicate nodes):\n");
scanf("%d",&x);
root=create(root,x);
break;
case 2: printf("\nInorder traversal:\n");
inorder(root);
printf("\nPreorder traversal:\n");
preorder(root);
printf("\nPostorder traversal:\n");
postorder(root);
printf("\n\n*********************************************");
break;
case 3: exit(0);
}
}
}
Menu
1. Insert
2. All traversals
3. Exit
Enter your choice:1
Enter node (do not enter duplicate nodes):
22
********************Output********************
32
Lab No:7
Menu
1. Insert
2. All traversals
3. Exit
Enter your choice:1
Enter node (do not enter duplicate nodes):
65
********************Output********************
Menu
1. Insert
2. All traversals
3. Exit
Enter your choice:1
Enter node (do not enter duplicate nodes):
25
********************Output********************
Menu
1. Insert
2. All traversals
3. Exit
Enter your choice:2
Inorder traversal:
22 25 65 234
Preorder traversal:
234 22 65 25
Postorder traversal:
25 65 22 234
*********************************************
33
Lab No:8
Description: A heap can be defined as a binary tree with keys assigned to its nodes, one
key per node, provided the following two conditions are met:
1. The shape property—the binary tree is essentially complete (or simply complete), i.e.,
all its levels are full except possibly the last level, where only some rightmost leaves
may be missing.
2. The parental dominance or heap property—the key in each node is greater than or
equal to the keys in its children. (This condition is considered automatically satisfied
for all leaves.)
I. SOLVED EXERCISE:
1). Write a program to construct a heap for a given list of keys using bottom-up heap
construction algorithm.
34
Lab No:8
ALGORITHM HeapBottomUp(H[1..n])
//Constructs a heap from the elements of a given array
//by the bottom-up algorithm
//Input: An array H[1..n] of orderable items
//Output: A heap H[1..n]
n
for i ← ⎝ [ downto 1
2
k ← i; v ← H[k]
heap ← false
while not heap and 2*k≤n do
j ← 2*k
if j<n //there are two children
if H[j] < H[j+1] j ← j+1
if v≥H[j]
heap ← true
else H[k] ← H[j]; k ← j
H[k] ← v
Time Efficiency:
Tworst(n)=2(n-log2(n+1)), where n is number of elements
Program
#include<stdio.h>
#include<conio.h>
void heapify(int h[],int n)
{
int i,k,v,heapify,j;
for(i=(n/2);i>=1;i--)
{
k=i;v=h[k];heapify=0;
while(heapify==0&&2*k<=n)
{
j=2*k;
if(j<n)
if(h[j]<h[j+1])
j=j+1;
if(v>=h[j])
heapify=1;
else
35
Lab No:8
{
h[k]=h[j];
k=j;
}
}
h[k]=v;
}
return;
}
void main()
{
int h[20],i,n;
clrscr();
printf("\nEnter the number of Elements:");
scanf("%d",&n);
printf("\nEnter the Elements:");
for(i=1;i<=n;i++)
scanf("%d",&h[i]);
printf("\ndisplay the array:");
for(i=1;i<=n;i++)
{
printf("%d\t",h[i]);
}
heapify(h,n);
printf("\nThe heap created:");
for(i=1;i<=n;i++)
{
printf("%d\t",h[i]);
}
getch();
}
36
Lab No:8
ADDITIONAL EXERCISES:
1) Write a program to check whether an array H[1..n] is a heap or not
2) Write a program for finding and deleting an element of a given value in a
heap.
3) Write a program to find and delete the smallest element in the max heap.
37
Lab No:9
Description: In time and space tradeoffs technique if time is at premium, we can pre-
compute the function’s values and store then in a table. In somewhat more general terms,
the idea is to preprocess the problem’s input, in whole or in part, and store the additional
information obtained to accelerate solving the problem afterward. We call this approach
input enhancement. The other type of technique that exploits space-for-time trade-offs
simply uses extra space to facilitate faster and/or more flexible access to the data. We call
this approach pre-structuring.
I. SOLVED EXERCISE:
1) Write a program to sort set of integers using comparison counting algorithm.
38
Lab No:9
Time Efficiency:
T(n)=O(n2), where n is number of integers
Program
#include <stdio.h>
void counting_sort(int A[])
{
int i, j;
int S[15], C[100];
for (i = 0; i <= n-1; i++)
C[i] = 0;
for (i = 0; i <= n-2; i++)
{
for (j = i+1; j <= n-1; j++)
{
if A[i]<A[j ]
Count[j ]←Count[j ]+ 1;
else Count[i]←Count[i]+ 1;
}
}
for (i = 0; i <= n-1; i++)
S[c[i]]=A[i];
printf("The Sorted array is : ");
for (i = 0; i <= n-1; i++)
printf("%d ", S[i]);
}
int main()
{
int n, k = 0, A[15], i;
printf("Enter the number of integers : ");
scanf("%d", &n);
printf("\nEnter the integers to be sorted :\n");
for (i = 1; i <= n; i++)
scanf("%d", &A[i]);
counting_sort(A);
printf("\n");
return 0;
}
39
Lab No:9
40
Lab No:10
I. SOLVED EXERCISE:
1) Write a program to find the Binomial Co-efficient using Dynamic Programming.
Time Efficiency:
T(n)=O(nk) for binomial coefficient of any number n & k
ALGORITHM Binomial(n,k)
// Computes C(n,k) by the dynamic programming algorithm
//Input: A pair of nonnegative integers n≥k≥0
//Output: The value of C(n,k)
for i ← 0 to n do
for j ← 0 to min(i,k) do
41
Lab No:10
if j=0 or j=i
C[i,j] ← C[i-1,j-1] + C[i-1,j]
return C[n,k]
Program
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int c[20][20];
void binomial(int n,int k)
{
int i,j;
for(i=0;i<=n;i++)
{
for(j=0;j<=min(i,k);j++)
{
if(j==0||j==i)
c[i][j]=1;
else
c[i][j]=c[i-1][j-1]+c[i-1][j];
}
}
}
void main()
{
int n,k,i,j;
clrscr();
printf("Enter the value of n\n");
scanf("%d",&n);
printf("Enter the value of k\n");
scanf("%d",&k);
if(n<k)
printf("Invalid input: n cannot be less than k\n");
else if(k<0)
printf("Invalid input: k cannot be less than 0\n");
else
{
binomial(n,k);
printf("Computed matrix is \n");
for(i=0;i<=n;i++)
{
42
Lab No:10
for(j=0;j<=min(i,k);j++)
printf("%d\t",c[i][j]);
printf("\n");
}
printf("binomial coefficient c[%d,%d]=%d\n",n,k,c[n][k]);
}
getch();
}
43
Lab No:11
I. SOLVED EXERCISE:
1) Write a program to find Minimum Cost Spanning Tree of a given undirected graph
using Prim’s algorithm.
44
Lab No:11
in the graph. The tree generated by the algorithm is obtained as the set of edges used for
the tree expansions.
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
VT ← {v0} // The set of tree vertices can be initialized with any vertex
ET ← Φ
for i ← 1 to |V| -1 do
find a minimum-weight edge e*=(v*,u*) among all the edges (u,v)
such that v is in VT and u is in V-VT
VT ← VT U {u*}
ET ← ET U{e*}
return ET
Time Efficiency:
T(n)=O(|E| log|V|), for a graph with E edges and V vertices, represented as adjacency
list
Program
#include<stdio.h>
#include<conio.h>
int a[50][50],t[50][50],root[50],parent[50],n,i,j,value,e=0,k=0;
int ivalue,jvalue,cost=0,mincost=0,TV[50],count=0,present=0;
main()
{
clrscr();
printf("\n\t\t\t PRIMS ALGORITHM\n");
TV[++count]=1;
read_cost();
prims();
display();
getch();
}
read_cost()
{
printf("\n Enter the number of vertices:");
45
Lab No:11
scanf("%d",&n);
printf("\n Enter cost adjacency matrix\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(i<j)
{
printf("(%d,%d):",i,j);
scanf("%d",&value);
a[i][j]=value;
if(value!=0)
e++;
}
else if(i>j)
a[i][j]=a[j][i];
else
a[i][j]=0;
}
prims()
{
while(e && k<n-1)
{
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(a[i][j]!=0)
{
int x,y;
x=check_reach(i);
y=check_reach(j);
if((x==1) && (y==0))
{
present=1;
if((a[i][j] < cost) || (cost==0))
{
cost=a[i][j];
ivalue=i;
jvalue=j;
}
}
}
}
46
Lab No:11
if(present==0) break;
a[ivalue][jvalue]=0;
a[jvalue][ivalue]=0;
e--;
TV[++count]=jvalue;
t[ivalue][jvalue]=cost;
k++;
present=cost=0;
}
}
display()
{
if(k==n-1)
{
printf("\n Minimum cost spanning tree is\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(t[i][j]!=0)
printf("\n(%d,%d):%d",i,j,t[i][j]);
mincost=mincost+t[i][j];
}
printf("\n Cost of this spanning tree:%d",mincost);
}
else
printf("\n Graph is not connected");
}
int check_reach(int v)
{
int p;
for(p=1;p<=count;p++)
if(TV[p]==v) return 1;
return 0;
}
47
Lab No:11
48
Lab No:11
49
Lab No:12
Objectives:
In this lab, student will be able to:
• Understand Backtracking & Branch and Bound design technique
• Apply this technique to examples like subset-sum problem and knapsack problem.
1) A way to provide, for every node of a state-space tree, a bound on the best value of the
objective function on any solution that can be obtained by adding further components
to the partially constructed solution represented by the node.
2) The value of the best solution seen so far.
If this information is available, we can compare a node’s bound value with the value of
the best solution seen so far. If the bound value is not better than the value of the best
solution seen so far-i.e., not smaller for a minimization problem and not larger for a
maximization problem-the node is nonpromising and can be terminated (some people say
the branch is “pruned”). Indeed, no solution obtained from it can yield a better solution
than the one already available. This is the principal idea of the branch-and-bound
technique.
In general, we terminate a search path at the current node in a state-space tree of a branch-
and-bound algorithm for any one of the following three reasons:
1) The value of the node’s bound is not better than the value of the best solution seen so
far.
2) The node represents no feasible solutions because the constraints of the problem are
already violated.
3) The subset of feasible solutions represented by the node consists of a single point (and
hence no further choices can be made)—in this case, we compare the value of the
objective function for this feasible solution with that of the best solution seen so far
and update the latter with the former if the new solution is better.
50
Lab No:12
I. SOLVED EXERCISE:
1) Write a program for n-Queens problem using backtracking technique.
ALGORITHM Backtrack(X[1..i])
//Gives a template of a generic backtracking algorithm
//Input: X[1..i] specifies first i promising components of a solution
//Output: All the tuples representing the problem’s solutions
Time Efficiency:
Size of state space tree
51
Lab No:12
Program
int place(int[],int);
void printsolution(int,int[]);
void main()
{
int n;
clrscr();
printf("Enter the no.of queens: ");
scanf("%d",&n);
nqueens(n);
getch();
}
void nqueens(int n)
{
int x[10],count=0,k=1;
x[k]=0;
while(k!=0)
{
x[k]=x[k]+1;
while(x[k]<=n&&(!place(x,k)))
x[k]=x[k]+1;
if(x[k]<=n)
{
if(k==n)
{
count++;
printf("\nSolution %d\n",count);
printsolution(n,x);
}
else
{
k++;
x[k]=0;
}
}
else
{
k--; //backtracking
}
}
return;
52
Lab No:12
}
int place(int x[],int k)
{
int i;
for(i=1;i<k;i++)
if(x[i]==x[k]||(abs(x[i]-x[k]))==abs(i-k))
return 0;
return 1;
}
void printsolution(int n,int x[])
{
int i,j;
char c[10][10];
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
c[i][j]='X';
}
for(i=1;i<=n;i++)
c[i][x[i]]='Q';
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%c\t",c[i][j]);
}
printf("\n");
}
}
53
Lab No:12
Solution 2
X X Q X
Q X X X
X X X Q
X Q X X
54
References:
1. Anany Levitin, Introduction to The Design and Analysis of Algorithms, 3rd
Edition, Pearson Education, India, 2012.
2.Ellis Horowitz and Sartaj Sahni, Computer Algorithms/C++, Second Edition,
University Press, 2007.
3. Thomas H. Cormen, Charles E. Leiserson, Ronal L, Rivest, Clifford Stein,
Introduction to Algorithms, PHI, 2nd Edition, 2006.
55