0% found this document useful (0 votes)
2 views

DAA Experiments

The document is a lab manual for the Design and Analysis of Algorithms course, detailing the fundamentals of algorithms, their design, analysis, and various sorting techniques such as Selection Sort, Bubble Sort, and Merge Sort. It covers algorithm characteristics, complexity analysis, and different design techniques including recursive and greedy methods. Additionally, it provides C programming examples for sorting algorithms and searching methods, along with lab questions for students to assess their understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

DAA Experiments

The document is a lab manual for the Design and Analysis of Algorithms course, detailing the fundamentals of algorithms, their design, analysis, and various sorting techniques such as Selection Sort, Bubble Sort, and Merge Sort. It covers algorithm characteristics, complexity analysis, and different design techniques including recursive and greedy methods. Additionally, it provides C programming examples for sorting algorithms and searching methods, along with lab questions for students to assess their understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

INTRODUCTION TO DESIGN AND ANALYSIS OF ALGORITHMS

An algorithm is a set of steps of operations to solve a problem performing calculation, data


processing, and automated reasoning tasks. It is an efficient method that can be expressed
within finite amount of time and space. An algorithm is the best way to represent the
solution of a particular problem in a very simple and efficient way. If we have an algorithm
for a specific problem, then we can implement it in any programming language,
meaning that the algorithm is independent from any programming languages.

Algorithm Design:

The important aspects of algorithm design include creating an efficient algorithm to solve a
problem in an efficient way using minimum time and space. To solve a problem, different
approaches can be followed. Some of them can be efficient with respect to time consumption,
whereas other approaches may be memory efficient. However, one has to keep in mind that
both time consumption and memory usage cannot be optimized simultaneously.

Problem Development Steps:


The following steps are involved in solvingcomputational problems.
 Problem definition
 Development of a model
 Specification of an Algorithm
 Designing an Algorithm
 Checking the correctness of an Algorithm
 Analysis of an Algorithm
 Implementation of an Algorithm
 Program testing
 Documentation

Characteristics of Algorithms:
The main characteristics of algorithms are asfollows:
 Algorithms must have a unique name
 Algorithms should have explicitly defined set of inputs and outputs
 Algorithms are well-ordered with unambiguous operations
 Algorithms halt in a finite amount of time. Algorithms should not run for
infinity, i.e., an algorithm must end at some point

Algorithm Analysis:
Algorithm analysis is an important part of computational complexity theory, which provides
theoretical estimation for the required resources of an algorithm to solve a specific
computational problem. Analysis of algorithms is the determination of the amount of time and
space resources requiredto execute it.

The Need for Analysis:


Algorithms are often quite different from one another, though the objectives of these
algorithms are the same. Analysis of algorithm is the process of analyzing the problem-solving

1
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

capability of the algorithm in terms of the time and size required. Generally, the following
types of analysis are performed –

 Worst-case − the maximum number of steps taken on any instance of size a.


 Best-case − the minimum number of steps taken on any instance of size a.
 Average case − the average number of steps taken on any instance of size a.

Complexity of an algorithm is analyzed in two perspectives: Time and Space:


Time Complexity:
It’s a function describing the amount of time required to run analgorithm in terms of the size
of the input.
Space Complexity:
It’s a function describing the amount of memory an algorithm takes in terms of the size of
input to the algorithm.

Asymptotic Notations:
Execution time of an algorithm depends on the instruction set, processor speed, disk I/O speed,
etc. Hence, we estimate the efficiency of an algorithm asymptotically. Different types of
asymptotic notations are used to represent the complexity of an algorithm. Following
asymptotic notations are used to calculate the running time complexity of an algorithm.
 O − Big Oh
 Ω − Big omega
 θ − Big theta
 − Little Oh
 ω − Little omega

Algorithm Design Techniques:


The following is a list of several popular designapproaches:
 Recursive
 Divide and Conquer
 Dynamic Programming
 Greedy Technique
 Brute Force
 Backtracking
 Branch and Bound

Recursive Algorithm:
This is one of the most interesting Algorithms as it calls itself with a smaller value as inputs
which it gets after solving for the current inputs. In simpler words, it’s an Algorithm that calls
itself repeatedly until the problem is solved.
Problems such as the Tower of Hanoi or DFS of a Graph can be easily solved by using these
Algorithms.

Divide and Conquer:


This is another effective way of solving many problems. In Divide and Conquer algorithms,
divide the algorithm into two parts; the first parts divide the problem on hand into smaller sub
2
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

problems of the same type. Then, in the second part, these smaller problems are solved and
then added together (combined) to produce the problem’s final solution.
Problems such as Binary Search, Quick Sort, and Merge Sort can be solved using this
technique.

Dynamic Programming:
These algorithms work by remembering the results of the past run and using them to find
new results. In other words, a dynamic programming algorithm solves complex problems
by breaking them into multiplesimple sub problems and then it solves each of them once and
then stores them for future use. Dynamic Programming is frequently related to Optimization
Problems. Problems such as Multistage Graphs, Optimal Binary Search Tress can be solved
using this technique.

Greedy Technique:
This is used to solve the optimization problem. Anoptimization problem is one in which there
is a given a set of input values, which are required either to be maximized or minimized
(known as objective), i.e. some constraints or conditions. It always makes the choice (greedy
criteria) looks best at the moment, to optimize a given objective. It doesn't always guarantee
the optimal solution however it generally produces a solution that is very close in value to the
optimal.
Problems such as Kruskal’s Minimum Spanning Tree (MST), Prim's Minimal Spanning Tree,
Dijkstra's Minimal Spanning Tree and Knapsack Problem can be solved using this technique.

Brute Force Algorithm:


This is one of the simplest algorithms in the concept. A brute force algorithm blindly iterates
all possible solutions to search one or more than one solution that may solve a function. Think
of brute force as using all possible combinations of numbers to open a safe.
Problems such as Selection Sort, convex hull can be solved using this technique.

Backtracking Algorithm:
Backtracking is a technique to find a solution to a problem in an incremental approach. It
solves problems recursively and tries to solve a problem by solving one piece of the
problem at a time. If one of the solutions fails, we remove it and backtrack to find another
solution. In other words,a backtracking algorithm solves a sub problem, and if it fails to solve
the problem,it undoes the last step and starts again to find the solution to the problem.
N-Queens problem is one good example to see Backtracking algorithm in action.

Branch and Bound:


In Branch & Bound algorithm a given sub problem, which cannot be bounded, has to be
divided into at least two new restricted sub problems. Branch and Bound algorithm are
methods for global optimization in non-convexproblems. Branch and Bound algorithms can
be slow, however in the worst casethey require effort that grows exponentially with problem
size.

3
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

1. SORT LIST OF NUMBERS USING SELECTION SORT

Aim:

To write a C program to perform Selection sort for any given list of numbers.

Description:

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, starting with the second
element, scan the elements to the right of it to find the smallest among them and swap it with the
second element.
Generally, on pass i (0  i  n-2), find the smallest element in A[i..n-1] and swap it with A[i]:
A[0]  A[1]  . . .  A[i-1] | A[i], . . . , A[min], . . ., A[n-1]
in their final positions the last n-i elements
after n-1 passes, the list is sorted.

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 ascending order
for i <- 0 to n-1 do
min <- i
for j <- i+1 to n-1 do
if a[j]<a[min] then
min <- j
swap a[i] and a[min]

Complexity:

Space Complexity: O(n)


Time Complexity: Average case and worst case - O(n)2 and best Case - O(n)

Program:

/*C program for selection sort*/


#include<stdio.h>
#include<conio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

4
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

void selectionSort(int arr[], int n)


{
int i, j, min_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i<=n-2; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j <= n-1; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
swap(&arr[min_idx], &arr[i]);
}
}

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Driver program to test above functions
int main()
{
int arr[100], n, i;
printf("Enter number of elements in the array:");
scanf("%d",&n);
printf("\nEnter array elements");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

5
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

Input/Output:

Lab viva questions:

1. What is an algorithm and explain its specifications?


2. What is time complexity and space complexity?
3. What is Brute force approach?
4. What are the applications of Brute force approach?
5. What is the time and space complexity of Selection sort?

6
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

2. SORT LIST OF NUMBERS USING BUBBLE SORT

Aim:

Write a C program to perform Bubble sort for any given list of numbers.

Description:

Bubble sort works on the repeatedly swapping of adjacent elements until they are not in the
intended order. It is called bubble sort because the movement of array elements is just like the
movement of air bubbles in the water. Bubbles in water rise up to the surface; similarly, the array
elements in bubble sort move to the end in each iteration.
Algorithm:

BubbleSort(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 ascending order
for all array elements
if arr[i] > arr[i+1]
swap(arr[i], arr[i+1])
end if
end for
return arr

Complexity:

Space Complexity: O(n)


Time Complexity: O(n)2

Program:

/*C program for selection sort*/


#include<stdio.h>
#include<conio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i<=n-2; i++)

7
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j <= n-1; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
swap(&arr[min_idx], &arr[i]);
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Driver program to test above functions
int main()
{
int arr[100], n, i;
printf("Enter number of elements in the array:");
scanf("%d",&n);
printf("\nEnter array elements");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

8
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

Input/Output:

Lab viva questions:

1. What is an algorithm and explain its specifications?


2. What is time complexity and space complexity?
3. What is Brute force approach?
4. What are the applications of Brute force approach?
5. What is the time and space complexity of Selection sort?

9
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

3. SEQUENTIAL SEARCH

Aim:

Write a C program to search given number in the list of numbers using sequential search.

Description:

Linear search or sequential search is a method for finding an element within a list. It sequentially
checks each element of the list until a match is found or the whole list has been searched.

Algorithm:

linear_search (list, value)


begin
for each item in the list
if match item == value
return the item's location
end if
end for
end

Complexity:

Space Complexity: O(n)


Time Complexity: Average case and worst case - O(n) and best case O(1)

Program:

/*C program for Sequential search*/


#include<stdio.h>
void Sequential(int arr[],int n ,int k)
{
int i;
for(i=0;i<n;i++)
{
if (arr[i]==k)
{
printf("\nElement %d found at location %d and search is said to be
successful",k,i+1);
break;
}
}
if(i>=n)
printf("\nelement %d is not found -1\n and search is said to be unsuccessful",k);
else

10
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

}
int main()
{
int n,a[20],i,k;
printf("Enter Size of array:");
scanf("%d",&n);
printf("\nEnter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter searching element:");
scanf("%d",&k);
Sequential(a,n,k);
return 0;
}

Input/Output:

Lab viva questions:

1. What is sequential search explain with an example?


2. What is time complexity and space complexity of sequential search?
3. What are the advantages and disadvantages of sequential search?
4. Where is sequential search is used?
5. What are the applications of sequential search?

11
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

4. MERGE SORT

Aim:

Write a C program to sort given list of numbers using merge sort.

Description:

Merge sort is yet another sorting algorithm that falls under the category of Divide and Conquer
technique. It is one of the best sorting techniques that successfully build a recursive algorithm.
In this technique, we segment a problem into two halves and solve them individually. After
finding the solution of each half, we merge them back to represent the solution of the main
problem.
Suppose we have an array A, such that our main concern will be to sort the subsection, which
starts at index p and ends at index r, represented by A[p..r].

Divide

If assumed q to be the central point somewhere in between p and r, then we will fragment the
subarray A[p..r] into two arrays A[p..q] and A[q+1, r].

Conquer

After splitting the arrays into two halves, the next step is to conquer. In this step, we individually
sort both of the subarrays A[p..q] and A[q+1, r]. In case if we did not reach the base situation,
then we again follow the same procedure, i.e., we further segment these subarrays followed by
sorting them separately.

Combine

As when the base step is acquired by the conquer step, we successfully get our sorted subarrays
A[p..q] and A[q+1, r], after which we merge them back to form a new sorted array [p..r].

Algorithm:

MERGE-SORT (A, LOW, HIGH)


If p<r
Then q → (p+ r)/2
MERGE-SORT (A, p, q)
MERGE-SORT (A, q+1,r)
MERGE (A, p, q, r)

Algorithm MERGE (A, p, q, r)


n 1 = q-p+1

12
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

n 2= r-q
create arrays [1.....n 1 + 1] and R [ 1.....n 2 +1 ]
for i ← 1 to n 1
do [i] ← A [ p+ i-1]
for j ← 1 to n2
do R[j] ← A[ q + j]
L [n 1+ 1] ← ∞
R[n 2+ 1] ← ∞
I←1
J←1
For k ← p to r
Do if L [i] ≤ R[j]
then A[k] ← L[ i]
i ← i +1
else A[k] ← R[j]
j ← j+1

Complexity:

Time complexity:

Best case Average case Worst case


O (nlogn) O (nlogn) O (nlogn)
Space complexity:
In case of merge sort, we need to build a temporary array to merge the sorted arrays. So the
space complexity is O(n).

Program:

/*C program for sorting given list of numbers using Merge sort*/
#include<stdio.h>
int b[5000];
void merge(int a[],int low,int mid,int high)
{
int i,j,k;
i=low;
j=mid+1;
k=low;
while(i<=mid && j<=high)
{
if(a[i]<=a[j])
b[k++]=a[i++];
else
b[k++]=a[j++];
}
while(i<=mid)

13
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

b[k++]=a[i++];
while(j<=high)
b[k++]=a[j++];
for(k=low;k<=high;k++)
a[k]=b[k];
}
void mergesort(int a[],int low,int high)
{
int mid;
if(low>=high)
return;
mid = (low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a,low,mid,high);
}
int main()
{
int n,a[5000],k;
double ts;
printf("\nSort given list of numbers using merge sort");
printf("\nEnter size of the array:");
scanf("%d",&n);
printf("\nEnter the array numbers:\n");
for(k=1;k<=n;k++)
scanf("%d",&a[k]);
mergesort(a,1,n);
printf("\n Sorted Numbers are:\n");
for(k=1;k<=n;k++)
printf("%d\t",a[k]);
return 0;
}

14
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

Input/Output:

Lab viva questions:


1. What is the principle of merge sort?
2. What algorithm design technique is used in merge sort?
3. What is the space complexity of merge sort?
4. What is the time complexity of merge sort?
5. What is divide and conquer strategy?

15
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

5. QUICK SORT

Aim:

Write a C program to sort given list of integers using quick sort.

Description:

Divide: Rearrange the elements and split arrays into two sub-arrays and an element in between
search that each element in left sub array is less than or equal to the average element and each
element in the right sub- array is larger than the middle element.

Conquer: Recursively, sort two sub arrays.

Combine: Combine the already sorted array.


Algorithm:

QUICKSORT (array A, int m, int n)


if (n > m) then
i ← a random index from [m,n]
swap A [i] with A[m]
o ← PARTITION (A, m, n)
QUICKSORT (A, m, o - 1)
QUICKSORT (A, o + 1, n)
Algorithm PARTITION (array A, int m, int n)
x ← A[m]
o←m
for p ← m + 1 to n do
if (A[p] < x) then
o←o+1
swap A[o] with A[p]
swap A[m] with A[o]
return o
Complexity:

Time complexity:
Best case Average case Worst case
O (nlogn) O (nlogn) O (n2)
Space complexity: O(n)

16
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

Program:

/*C Program for sort list integers using Quick sort*/


#include<stdio.h>
void Exch(int *p,int *l){
int temp = *p;
*p = *l;
*l = temp;
}
void Quicksort(int a[200],int low,int high){
int key,i,j;
if (low > high)
return;
key = low;
i=low;
j = high;
while(i<j){
while(a[i]<=a[key])
i=i+1;
while(a[j]>a[key])
j=j-1;
if (i<j)
Exch(&a[i],&a[j]);
}
Exch(&a[j],&a[key]);
Quicksort(a,low,j-1);
Quicksort(a,j+1,high);
}
int main()
{
int n,a[100],k;
printf("\nSort list of integers using quick sort");
printf("\nEnter how many numbers :");
scanf("%d",&n);
printf("\nEnter the array numbers :");
for(k=0;k<n;k++){
scanf("%d",&a[k]);
}
printf("\n Array elements before sorting :");
for(k=0;k<n;k++){
printf("%d\t",a[k]);
}
printf("\n");
Quicksort(a,0,n);
printf("sorted array elements are :");
for(k=0;k<n;k++){

17
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

printf("%d\t",a[k]);
}
return 0;
}

Input/Output:

Lab viva questions:

1. What is the principle of quick sort?


2. What algorithm design technique is used in quick sort?
3. What is the space complexity of quick sort?
4. What is the time complexity of quick sort?
5. Why it is called partition exchange sort?

18
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

6. KNAPSACK PROBLEM USING GREEDY METHOD

Aim:

Write a C program to find solution for Knapsack problem using Greedy method..

Description:

In this method, the Knapsack’s filling is done so that the maximum capacity of the knapsack is
utilized so that maximum profit can be earned from it. The knapsack problem using the Greedy
Method is referred to as:
Given a list of n objects, say {I1, I2,……, In) and a knapsack (or bag).
The capacity of the knapsack is M.
Each object Ij has a weight wj and a profit of pj
If a fraction xj (where x ∈ {0…., 1)) of an object Ij is placed into a knapsack, then a profit of pjxj
is earned.
The problem (or Objective) is to fill the knapsack (up to its maximum capacity M), maximizing
the total profit earned.
Mathematically: Note that the value of xj will be any value between 0 and 1 (inclusive). If any
object Ij is completely placed into a knapsack, its value is 1 (xj = 1). If we do not pick (or select)
that object to fill into a knapsack, its value is 0 ( xj = 0). Otherwise, if we take a fraction of any
object, then its value will be any value between 0 and 1.
Algorithm:

GreedyKnapsack(m,n)
{
for i = 1 to n do
{
X[i] = 0.0;
}
Cu = m;
for i=1 to n do
{
If w[i]<cu then
{
X[i] = 1.0;
Cu = cu – w[i];
}
}
If i<=n then

19
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

X[i] = cu/w[i];
}

Program:

/*C program to implement Knapsock Problem using Greedy method*/


#include<stdio.h>
void knapsack(int n,float weight [],float profit[],float capacity)
{
float x[20],tp=0;
int i,j,u;
u=capacity;
for(i=0;i<n;i++)
x[i]=0.0;
for(i=0;i<n;i++)
{
if(weight[i]>u)
break;
else
{
x[i]=1.0;
tp=tp+profit[i];
u=u-weight[i];
}
}
if(i<n)
x[i]=u/weight[i];
tp=tp+(x[i]*profit[i]);
printf("\n the result vector is:");
for(i=0;i<n;i++)
printf("%f \t",x[i]);
printf("\n maximum profit is :%f",tp);
}
int main()
{
float weight[20],profit[20],capacity;
int num,i,j;
float ratio[20],temp;
printf("\n Knapsack problem using Greedy method");
printf("\n Enter the no.of objects:");
scanf("%d",&num);
printf("\n Enter the wts and profits of each object:");
for(i=0;i<num;i++)
{
scanf("%f%f",&weight[i],&profit[i]);
}

20
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

printf("\n Enter the capacity of knapsack:");


scanf("%f",&capacity);
for(i=0;i<num;i++)
{
ratio[i]=profit[i]/weight[i];
}
for(i=0;i<num;i++)
{
for(j=i+1;j<num;j++)
{
if(ratio[i]<ratio[j])
{
temp=ratio[j];
ratio[j]=ratio[i];
ratio[i]=temp;
temp=weight[j];
weight[j]=weight[i];
weight[i]=temp;
temp=profit[j];
profit[j]=profit[i];
profit[i]=temp;
}
}
}
knapsack(num, weight, profit, capacity);
return 0;
}

Input/Output:

21
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

Lab viva questions:

1. What is the principle of optimality?


2. What is feasible solution?
3. What is Greedy method?
4. What are the applications of greedy method?
5. What is another name for fractional knapsack problem?

22
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

7. MINIMUM COST SPANNING TREE USING PRIM’S ALGORITHM

Aim:

Write a C program to find minimum cost spanning tree for a given graph using Prim’s algorithm.

Description:

Prim's Algorithm is a greedy algorithm that is used to find the minimum spanning tree from a
graph. Prim's algorithm finds the subset of edges that includes every vertex of the graph such that
the sum of the weights of the edges can be minimized.

Prim's algorithm starts with the single node and explores all the adjacent nodes with all the
connecting edges at every step. The edges with the minimal weights causing no cycles in the
graph got selected.

Algorithm:

Step 1: Select a starting vertex


Step 2: Repeat Steps 3 and 4 until there are fringe vertices
Step 3: Select an edge 'e' connecting the tree vertex and fringe vertex that has minimum weight
Step 4: Add the selected edge and the vertex to the minimum spanning tree T
[END OF LOOP]
Step 5: EXIT

Complexity:

The time complexity of Prim’s algorithm will be in O (|E| log |V|).

Program:

/*C program to find minimum cost spanning tree using Prim's Algorithm*/
#include<stdio.h>
int main()

23
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

{
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
printf("Minimum cost spanning tree using Prim's Algorithm");
printf("\nEnter the no.of nodes/vertices: ");
scanf("%d",&n);
printf("\nEnter the adjacent matrix:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if (cost[i][j]==0)
cost[i][j]=999;
}
}
visited[1]=1;
printf("\n Minimum cost spanning tree using prim's algorithm");
while(ne<n)
{
for(i=1,min=999;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
if(visited[i]!=0)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
if(visited[u]==0||visited[v]==0)
{
printf("\n Edge %d: (%d %d) cost:%d",ne++,a,b,min);
mincost+=min;
visited[b]=1;
}

cost[a][b]=cost[b][a]=999;
}
printf("\n minimum cost= %d",mincost);
return 0;
}

24
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

Input/Output:

Lab viva questions:

1. What is spanning tree?


2. How many spanning trees are generated for a given weighted undirected graph?
3. What is MST?
4. What are the applications of MST?
5. What are the advantages and disadvantages of MST?
6. What is the principle of Prim’s algorithm?
7. What are the ways to represents of graph?
8. What is the input of Prim’s algorithm?
9. What is the output of the Prim’s algorithm?

25
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

8. MINIMUM COST SPANNING TREE USING KRUSKAL’S ALGORITHM

Aim:

Write a C program to find minimum cost spanning tree for a given graph using Kruskal’s
algorithm.

Description:

Kruskal's Algorithm is a greedy algorithm that is used to find the minimum spanning tree from a
graph. In Kruskal's algorithm, we start from edges with the lowest weight and keep adding the
edges until the goal is reached. The steps to implement Kruskal's algorithm are listed as follows -

First, sort all the edges from low weight to high.


Now, take the edge with the lowest weight and add it to the spanning tree. If the edge to be added
creates a cycle, then reject the edge.
Continue to add the edges until we reach all vertices, and a minimum spanning tree is created.
Algorithm:

Step 1: Create a forest F in such a way that every vertex of the graph is a separate tree.
Step 2: Create a set E that contains all the edges of the graph.
Step 3: Repeat Steps 4 and 5 while E is NOT EMPTY and F is not spanning
Step 4: Remove an edge from E with minimum weight
Step 5: IF the edge obtained in Step 4 connects two different trees, then add it to the forest F
(for combining two trees into one tree).
ELSE
Discard the edge
Step 6: END

Complexity:

The time complexity of Kruskal's algorithm is O(E logE) or O(V logV), where E is the no. of
edges, and V is the no. of vertices.
Program:

26
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

/*C program to find minimum cost spanning tree using Kruskal's Algorithm*/
#include<stdio.h>
#include<stdlib.h>
int i,j,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);
int main()
{
printf("Minimum cost spanning tree using Kruskal's Algorithm\n");
printf("\nEnter the no of virtices");
scanf("%d",&n);
printf("\nEnter the cost adjacency matrix");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if (cost[i][j]==0)
cost[i][j]=999;
}
}
printf("\nThe edges of minimum cost spanning tree are \n");
while(ne<n)
{
for(i=1,min=999;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find(u);
v=find(v);
if(uni(u,v))
{
printf("%d edges (%d,%d)=%d \n",ne++,a,b,min);
mincost+=min;
}
cost[a][b]=cost[b][a]=999;
}

27
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

printf("\n minimum cost = %d \n",mincost);


}
int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}
int uni(int i,int j)
{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}
Input/Output:

Lab viva questions:


1. What is the principle of Kruskal’s algorithm?
2. What is the difference between adjancy matrix and adjancy list?
3. What is the time complexity of Kruskal’s algorithm?
4. What is the time complexity of Prim’s algorithm?
5. Compare and contract Kruskal’s and Prim’s algorithms?

28
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

9. DIJKSTRA’S ALGORITHM

Aim:

To write a c program to find shortest paths from one vertex to remaining all other vertices using
Dijkstra’s algorithm.

Description:

Dijkstra's Algorithm is a Graph algorithm that finds the shortest path from a source vertex to all
other vertices in the Graph (single source shortest path). It is a type of Greedy Algorithm that
only works on Weighted Graphs having positive weights.
Algorithm:

Dijkstra(G, S)
for each vertex V in G
distance[V] <- infinite
previous[V] <- NULL
If V != S, add V to Priority Queue Q
distance[S] <- 0

while Q IS NOT EMPTY


U <- Extract MIN from Q
for each unvisited neighbour V of U
tempDistance <- distance[U] + edge_weight(U, V)
if tempDistance < distance[V]
distance[V] <- tempDistance
previous[V] <- U
return distance[], previous[]

29
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

Complexity:

The time complexity of Dijkstra's Algorithm is O(V2) with the help of the adjacency matrix
representation of the graph. This time complexity can be reduced to O((V + E) log V) with the
help of an adjacency list representation of the graph, where V is the number of vertices and E is
the number of edges in the graph.

Program:

/*C program to find find shortest paths from one vertex to remaining all other vertices using
Dijkstra's algorithm */
#include<stdio.h>
#define infinity 999
void dij(int n,int v,int cost[20][20],int dist[]){
int i,u,count,w,flag[20],min;
for(i=1;i<=n;i++)
flag[i]=0, dist[i]=cost[v][i];
count = 2;
while(count<=n)
{
min=99;
for(w=1;w<=n;w++)
if(dist[w]<min && !flag[w])
{
min=dist[w];
u=w;
}
flag[u]=1;
count++;
for(w=1;w<=n;w++)
if((dist[u]+cost[u][w]<dist[w]) && !flag[w])
dist[w]=dist[u]+cost[u][w];
}
}
int main(){
int n,v,i,j,cost[20][20],dist[20];
printf("Shortest paths from one vertex to remaining all other vertices using Dijkstra's
algorithm ");
printf("\nEnter the number of nodes/vertices: ");
scanf("%d",&n);
printf("\nEnter the cost matrix: \n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)

30
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

cost[i][j]=infinity;
}
printf("\n Enter the source matrix/vertices");
scanf("%d",&v);
dij(n,v,cost,dist);
printf("\n shortest path: \n");
for(i=1;i<=n;i++)
if(i!=v)
printf("%d->%d, cost=%d \n",v,i,dist[i]);
}
Input/Output:

Lab viva questions:

1. What is the difference between Greedy method and Divide and conquer method?
2. What is single source shortest path problem?
3. What are the advantages and disadvantages of Dijkstr’s algorithm?
4. What is the time complexity of Dijkstr’s algorithm?
5. What are the applications of single source shortest path problem?

31
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

10. FLOYD’S ALGORITHM

Aim:

To write a c program to find the shortest path between all pairs of vertices using Floyd’s
algorithm.

Description:

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

Floyd’s(G,n)
{
n = no of vertices
A = matrix of dimension n*n
for k = 1 to n
for i = 1 to n
for j = 1 to n
Ak[i, j] = min (Ak-1[i, j], Ak-1[i, k] + Ak-1[k, j])
return A
}

Complexity:

There are three loops. Each loop has constant complexities. So, the time complexity of the
Floyd-Warshall algorithm is O(n3).
The space complexity of the Floyd-Warshall algorithm is O(n2).

32
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

Program:

/* C progrm for find shortest distance between all pair of vertices using Floyd's algorithm*/
#include<stdio.h>
void floyd(int[10][10],int);
int min(int,int);
int main()
{
int n,a[10][10],i,j;
printf("shortest distance between all pair of vertices using Floyd's algorithm");
printf("\nEnter the no.of nodes :");
scanf("%d",&n);

printf("\n Note:\n1. 0 if i=j\n2. The cost of directed edge(i,j) if i not eqal to j and
(i,j)belongs to E\n3. 999 if i not equal to j and (i,j)not belongs to E");

printf("\nEnter the cost adjacency matrix\n");


for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
floyd(a,n);
}
void floyd(int a[10][10],int n)
{
int d[10][10],i,j,k;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
d[i][j]=a[i][j];
}
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
d[i][j]=min(d[i][j],d[i][k]+d[k][j]);
}
}
}
//cout<<"\nThe distance matrix is\n";
printf("\n The distance matrix is\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{

33
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

printf("%d\t",d[i][j]);
}
printf("\n");
}
}
int min (int a,int b)
{
if(a<b)
return a;
else
return b;
}

Input/Output:

Lab viva questions:

1. What is the difference between Greedy method and Dynamic programming?


2. What is all pairs shortest paths problem?
3. What are the advantages and disadvantages of all pairs shortest paths problem?
4. What is the time complexity of all pairs shortest paths problem?
5. What are the applications of all pairs shortest paths problem?

34
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

11. N – QUEENS PROBLEM

Aim:

To write a c program to implement the N-Queens problem using backtracking.

Description:
N - Queens problem is to place n - queens in such a manner on an n x n chessboard that no
queens attack each other by being in the same row, column or diagonal.
Algorithm:
Place (k, i)
{
For j ← 1 to k - 1
do if (x [j] = i)
or (Abs x [j]) - i) = (Abs (j - k))
then return false;
return true;
}
N - Queens (k, n)
{
For i ← 1 to n
do if Place (k, i) then
{
x [k] ← i;
if (k ==n) then
write (x [1....n));
else
N - Queens (k + 1, n);
}
}

Complexity:

Time Complexity: O(N!)


Space complexity: O(N2)

35
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

Program:

/* C program for N-Queens problem*/


#include<stdio.h>
#include<math.h>
int a[30],count=0;
int place(int pos)
{
int i;
for(i=1;i<pos;i++)
{
if((a[i]==a[pos])||((abs(a[i]-a[pos])==abs(i-pos))))
return 0;
}
return 1;
}
void print_sol(int n)
{
int i,j;
count++;
printf("\n\nSolution #%d:\n",count);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(a[i]==j)
printf("Q\t");
else
printf("*\t");
}
printf("\n");
}
}
void queen(int n)
{
int k=1;
a[k]=0;
while(k!=0)
{
a[k]=a[k]+1;
while((a[k]<=n)&&!place(k))
a[k]++;
if(a[k]<=n)
{
if(k==n)
print_sol(n);

36
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

else
{
k++;
a[k]=0;
}
}
else
k--;
}
}
int main()
{
int i,n;
printf("N-Queens problem\n");
printf("Enter the number of Queens:");
scanf("%d",&n);
queen(n);
printf("\nTotal solutions=%d",count);
return 0;
}
Input/Output:

37
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

Lab viva questions:

1. What is backtracking?
2. What is the difference between dynamic programming and backtracking?
3. What is n-queens problem?
4. What is the time complexity of n-queens problem?
5. What are the advantages and disadvantages of backtracking?
6. What are the applications of backtracking?

38
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

12. SUM OF SUBSETS PROBLEM

Aim:

To write a c program for sum of subjects problem for given set of distinct numbers by using
backtracking.

Description:
Given the set of n positive integers, W = {w1, w2, …, wn}, and given a positive integer M, the
sum of the subset problem can be formulated as follows (where wi and M correspond to item
weights and knapsack capacity in the knapsack problem):

Numbers are sorted in ascending order, such that w1 < w2 < w3 < …. < wn. The solution is often
represented using the solution vector X.
Algorithm:

SUB_SET_PROBLEM(i, sum, W, remSum)


// Description : Solve sub of subset problem using backtracking
// Input : W: Number for which subset is to be computed, i: Item index, sum : Sum of integers
//selected so far remSum : Size of remaining problem i.e. (W – sum)
// Output : Solution tuple X

if FEASIBLE_SUB_SET(i) == 1 then
if (sum == W) then
print X[1…i]
end
else

X[i + 1] ← 1
SUB_SET_PROBLEM(i + 1, sum + w[i] + 1, W, remSum – w[i] + 1 )
X[i + 1] ← 0 // Exclude the ith item
SUB_SET_PROBLEM(i + 1, sum, W, remSum – w[i] + 1 )

end

39
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

function FEASIBLE_SUB_SET(i)

if (sum + remSum ≥ W) AND (sum == W) or (sum + w[i] + 1 ≤ W) then

return 0

end

return 1
Complexity:

Time Complexity:
It is intuitive to derive the complexity of sum of the subset problem. In the state-space tree, at
level i, the tree has 2i nodes. So, given n items, the total number of nodes in the tree would be 1
+ 2 + 22 + 23 + .. 2n.
T(n) = 1 + 2 + 22 + 23 + .. 2n = 2n+1 – 1 = O(2n)
Thus, sum of sub set problem runs in exponential order.

Space Complexity: O(n)

Program:

/* C program for Sum of subsets problem using backtracking*/


#include<stdio.h>
#define TRUE 1
#define FALSE 0
int inc[50],w[50],sum,n;
int promising(int i,int wt,int total) {
return(((wt+total)>=sum)&&((wt==sum)||(wt+w[i+1]<=sum)));
}
void sumset(int i,int wt,int total) {
int j;
if(promising(i,wt,total)) {
if(wt==sum) {
printf("\n{\t");
for (j=0;j<=i;j++)
if(inc[j])
printf("%d\t",w[j]);
printf("}\n");
} else {
inc[i+1]=TRUE;
sumset(i+1,wt+w[i+1],total-w[i+1]);
inc[i+1]=FALSE;
sumset(i+1,wt,total-w[i+1]);
}
}

40
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

}
int main() {
int i,j,n,temp,total=0;
printf("Sum of subsets problem using backtracking\n");
printf("\n Enter how many numbers:\n");
scanf("%d",&n);
printf("\n Enter %d numbers to the set:\n",n);
for (i=0;i<n;i++) {
scanf("%d",&w[i]);
total+=w[i];
}
printf("\n Input the sum value to create sub set:\n");
scanf("%d",&sum);
for (i=0;i<=n;i++)
for (j=0;j<n-1;j++)
if(w[j]>w[j+1]) {
temp=w[j];
w[j]=w[j+1];
w[j+1]=temp;
}
if((total<sum))
printf("\n Subset construction is not possible"); else {
for (i=0;i<n;i++)
inc[i]=0;
printf("\n The solution using backtracking is:\n");
sumset(-1,0,total);
}
}
Input/Output:

41
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

Lab viva questions:

1. What is backtracking?
2. What is the difference between dynamic programming and backtracking?
3. What is n-queens problem?
4. What is the time complexity of n-queens problem?
5. What are the advantages and disadvantages of backtracking?
6. What are the applications of backtracking?

42
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

EXPERIMENTS BEYOND THE SYLLABUS


1. SORT STUDENT DATA BASED ON MARKS USING SELECTION SORT

Aim:

To write a C program to sort student data in descending order based on marks using selection
sort.

Description:

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, starting with the
second element, scan the elements to the right of it to find the smallest among them and swap
it with the second element.
Generally, on pass i (0  i  n-2), find the smallest element in A[i..n-1] and swap it with A[i]:
A[0]  A[1]  . . .  A[i-1] | A[i], . . . , A[min], . . ., A[n-1]
in their final positions the last n-i elements
after n-1 passes, the list is sorted.

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 ascending order
for i <- 0 to n-1 do
min <- i
for j <- i+1 to n-1 do
if a[j]<a[min] then
min <- j
swap a[i] and a[min]

Complexity:

Time complexity:

Best Case Average Case Worst Case


O(n2) O(n2) O(n2)

Space Complexity: O(n)

43
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

Program:

/*C Program for sorting student data in descending order based on marks using Selection
sort*/
#include<stdio.h>
struct student{
char name[20];
int roll;
float marks;
};
int main(){
struct student s[20],temp;
int i,j,n,min;
printf("enter n:");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("enter your name roll and marks :");
scanf("%s%d%f",&s[i].name,&s[i].roll,&s[i].marks);
}
for(i=0;i<=n-2;i++){
min=i;
for(j=i+1;j<=n-1;j++)
if(s[j].marks>s[min].marks)
min=j;

temp = s[min];
s[min] = s[i];
s[i] = temp;
}
printf("sorted records are: \n");
printf("\n name \t roll \t marks \n");
for(i=0;i<n;i++){
printf("%s\t",s[i].name);
printf("%d\t",s[i].roll);
printf("%.2f\n",s[i].marks);
}
return 0;
}

44
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

Input/Output:

Lab viva questions:

1. What are important problem types? (or) Enumerate some important types of
problems.
2. Name some basic Efficiency classes?
3. What are algorithm design techniques?
4. What is the relationship between order of growth of functions?
5. What is pseudocode?

45
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

2. SORT EMPLOYEE DATA BASED ON SALARY USING BUBBLE SORT

Aim:

Write a C program to sort employee salary in ascending order using Bubble sort.

Description:

Bubble sort works on the repeatedly swapping of adjacent elements until they are not in the
intended order. It is called bubble sort because the movement of array elements is just like the
movement of air bubbles in the water. Bubbles in water rise up to the surface; similarly, the array
elements in bubble sort move to the end in each iteration.
Algorithm:

BubbleSort(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 ascending order
for all array elements
if arr[i] > arr[i+1]
swap(arr[i], arr[i+1])
end if
end for
return arr

Complexity:

Space Complexity: O(n)


Time Complexity: O(n)2

Program:

/*C Program for sorting employee data based on salary in ascending order using Bubble sort*/
#include<stdio.h>
struct employee
{
char name[20];
char id[20];
float sal;
};
int main()
{
struct employee s[20], temp;
int i,j,n;
printf("enter n:");
scanf("%d",&n);

46
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

for(i=0;i<n;i++)
{
printf("enter name, id and salary of the employee:");
scanf("%s%s%f",&s[i].name,&s[i].id,&s[i].sal);
}
for(i=0;i<=n-2;i++){
for(j=0;j<=n-2-i;j++){
if(s[j+1].sal<s[j].sal){
temp = s[j];
s[j] = s[j+1];
s[j+1] = temp;
}
}
}
printf("sorted records are: \n");
printf("\n name \t roll \t marks \n");
for(i=0;i<n;i++){
printf("%s\t",s[i].name);
printf("%s\t",s[i].id);
printf("%.2f\n",s[i].sal);
}
return 0;
}

Input/Output:

47
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

Lab viva questions:

1. What is recursive and non-recursive algorithm?


2. What is the worst case, average case and best case time complexity of bubble sort?
3. What is the space complexity of bubble sort?
4. What are the applications of bubble sort?
5. What is bubble sort?

48
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

3. SEARCHING STUDENT RECORED BASED ON ROLL NUMBER USING


LINEAR SEARCH

Aim:

Write a C program to search student record based on roll number using linear search.

Description:

Linear search or sequential search is a method for finding an element within a list. It sequentially
checks each element of the list until a match is found or the whole list has been searched.

Algorithm:

linear_search (list, value)


begin
for each item in the list
if match item == value
return the item's location
end if
end for
end

Program:

/*C Program for searching student record based on roll number using Linear search*/
#include<stdio.h>
#include<String.h>
struct student{
char name[20];
char roll[20];
float marks;
};

int main(){
struct student s[20],temp;
int i,j,n;
char k[20];
printf("\nEnter number of student records:");
scanf("%d",&n);
printf("\nEnter your name roll-number and marks for %d students :", n);
for(i=0;i<n;i++){
scanf("%s%s%f",&s[i].name,&s[i].roll,&s[i].marks);
}
printf("\nEnter roll number of the student as a key :");
scanf("%s",&k);

49
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

for(i=0;i<=n;i++){
if(strcmp(s[i].roll,k) == 0 ){
printf("\nStudent record found: \n");
printf("%s\t%s\t%.2f",s[i].name,s[i].roll,s[i].marks);
break;
}
}
if(i+1>n)
printf("\n Student record not found ");
return 0;
}

Input/Output:

Lab viva questions:

1. What is recursive and non-recursive algorithm?


2. What is the worst case, average case and best case time complexity of linear search?
3. What is the space complexity linear search?
4. What are the applications of linear search?
5. What are the advantages and disadvantages of linear search?

50
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

4. BINARY SEARCH USING DIVIDE AND CONQUER

Aim: Write a C program to search given number using binary search.

Description:

This search algorithm works on the principle of divide and conquer, since it divides the array
into half before searching. For this algorithm to work properly, the data collection should be in
the sorted form.
Algorithm:

binary_search(A, lowerBound, upperBound, x)


{
A ← sorted array
n ← size of array
x ← value to be searched

Set lowerBound = 1
Set upperBound = n

while x not found


if upperBound < lowerBound
EXIT: x does not exists.

set midPoint = lowerBound + ( upperBound - lowerBound ) / 2

if A[midPoint] < x
set lowerBound = midPoint + 1

if A[midPoint] > x
set upperBound = midPoint - 1

if A[midPoint] = x
EXIT: x found at location midPoint
end while
}

Complexity:

Time complexity:

Best Case Average Case Worst Case


O(1) O(logn) O(logn)

Space Complexity: O(n)

51
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

Program:

/*C program for Binary search using Divide and Conquer method*/
#include<stdio.h>
void result(int flag,int mid,int k)
{
if(flag == 1)
printf("%d is found at index %d",k,mid+1);
else
printf("%d is not found" , k);
}
void binarysearch(int a[100],int low,int high,int k)
{
int mid,flag=0;
while(low<=high)
{
mid = (low+high)/2;
if(a[mid] == k)
{
flag = 1;
break;
}
else if(a[mid]>=k)
high = mid-1;
else
low = mid+1;
}
result(flag,mid,k);
}
int main()
{
int i,n,a[30],k;
printf("Enter the size of array :");
scanf("%d",&n);
printf("\nEnter the %d elements",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter the searching element :");
scanf("%d",&k);
binarysearch(a,0,n,k);
}

52
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

Input/Output:

Lab viva questions:

1. What is recursive and non-recursive algorithm?


2. What is principle of binary search?
3. What is the worst case, average case and best case time complexity of binary search?
4. What is the space complexity binary search?
5. What are the applications of binary search?
6. What are the advantages and disadvantages of binary search?

53
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

5. 0/1 KNAPSACK PROBLEM

Aim:

Write a C program to find optimal solution of the bag or container using 0/1 knapsack problem
with the help of dynamic programming.

Description:

Given N items where each item has some weight and profit associated with it and also given a
bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items
into the bag such that the sum of profits associated with them is the maximum possible.

Note: The constraint here is we can either put an item completely into the bag or cannot put it at
all [It is not possible to put a part of an item into the bag].

Algorithm:

knap(int i,int j)
{
int value;
if(v[i][j]<0)
{
if(j<w[i])
value=knap(i-1,j);
else
value=max(knap(i-1,j),p[i]+knap(i-1,j-w[i]));
v[i][j]=value;
}
return(v[i][j]);
}

Complexity:

Time Complexity:
O(N * W) - As redundant calculations of states are avoided.
Space complexity:
O(N * W) + O(N) - The use of a 2D array data structure for storing intermediate states and O(N)
auxiliary stack space(ASS) has been used for recursion stack.

Program:

/*Cprogram for o/1 knapsack problem using dynamic programming*/


#include<stdio.h>
int w[10],p[10],v[10][10],n,i,j,cap,x[10]={0};
int max(int i,int j)

54
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

{
return ((i>j)?i:j);
}
int knap(int i,int j)
{
int value;
if(v[i][j]<0)
{
if(j<w[i])
value=knap(i-1,j);
else
value=max(knap(i-1,j),p[i]+knap(i-1,j-w[i]));
v[i][j]=value;
}
return(v[i][j]);
}
int main()
{
int profit,count=0;
printf("0/1 knapsack problem using dynamic programming\n");
printf("\nEnter the number of objects ");
scanf("%d",&n);
printf("Enter the profit and weights of the elements \n ");
for(i=1;i<=n;i++)
{
printf("\nEnter profit and weight for object no %d :",i);
scanf("%d%d",&p[i],&w[i]);
}
printf("\nEnter the capacity ");
scanf("%d",&cap);
for(i=0;i<=n;i++)
for(j=0;j<=cap;j++)
if((i==0)||(j==0))
v[i][j]=0;
else
v[i][j]=-1;
profit=knap(n,cap);
i=n;
j=cap;
while(j!=0&&i!=0)
{
if(v[i][j]!=v[i-1][j])
{
x[i]=1;
j=j-w[i];
i--;

55
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL

}
else
i--;
}
printf("object included are \n ");
printf("Sl.no\tweight\tprofit\n");
for(i=1;i<=n;i++)
if(x[i])
printf("%d\t%d\t%d\n",++count,w[i],p[i]);
printf("Total profit = %d\n",profit);
}

Input/Output:

Lab viva questions:

1. What is the difference between greedy method and dynamic programming?


2. What is fractional knapsack problem?
3. What is 0/1 knapsack problem?
4. What is optimal solution?
5. What is the time complexity of 0/1 knapsack problem?

56

You might also like