DAA Experiments
DAA Experiments
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.
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.
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 –
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
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.
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.
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.
3
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL
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:
Program:
4
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL
5
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL
Input/Output:
6
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL
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:
Program:
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:
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:
Complexity:
Program:
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:
11
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL
4. MERGE SORT
Aim:
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:
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:
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:
15
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL
5. QUICK SORT
Aim:
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.
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:
17
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL
printf("%d\t",a[k]);
}
return 0;
}
Input/Output:
18
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL
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:
20
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL
Input/Output:
21
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL
22
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL
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:
Complexity:
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:
25
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL
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 -
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
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
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:
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
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");
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:
34
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL
Aim:
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:
35
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL
Program:
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
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
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:
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)
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.
Program:
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
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
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:
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:
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
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:
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
48
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL
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:
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:
50
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL
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:
Set lowerBound = 1
Set upperBound = n
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:
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:
53
DEPARTMENT OF CSE KSRMCE DAA LAB MANUAL
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:
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:
56