DAA-Lab File
DAA-Lab File
ENGINEERING COLLEGE
NAAC ACCREDITED
DEPARTMENT OF COMPUTER SCIENCE
ENGINEERING & ALLIED
PRACTICAL FILE
SESSION: 2024-2025
INDEX
Sr. No. Name of the Practical Date of Remarks
Practical
Write a program in C for Recursive Binary & Linear
1 Search.
Vision
To provide affordable quality education and offers need based, value based and career based
programs and produces technocrats who are independent and self-sufficient and are capable
Mission
DM1.To develops young aspirants into skilled competent and socially responsible citizens.
DM2.To guides the construction of a strong nation by educating them in a variety of technical
4. Sign in the laboratory login register, write the TIME-IN, and occupy the
computer system allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the
lab observation note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff,
must maintain the discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded
systems, which should be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode
during the lab sessions. Misuse of the equipment, misbehaviors with the
staff and systems etc., will attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to
go out; if anybody found loitering outside the lab / class without permission
during working hours will be treated seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she
leaves the lab after completing the task (experiment) in all aspects. He/she
must ensure the system / seat is kept properly.
Experiment No. 1
Program Name:
Theory Concept:
The Linear Search, or sequential search, is simply examining each element in a list one by one
until the desired element is found. The Linear Search is not very efficient. If the item of data to
be found is at the end of the list, then all previous items must be read and checked before the item
that matches the search criteria is found.
Implementation:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,temp,ser,a[100],opt,beg,mid,end;
clrscr();
printf("enter the no of elements to be entered");
scanf("%d",&temp);
for(i=0;i<temp;i++)
{
printf("\n number %d ",i+1);
scanf("%d",&a[i]);
}
printf("enter the no to be searched");
scanf("%d",&ser);
for(i=0;i<temp;i++)
{
if(ser==a[i])
{
printf("\n number exists at location %d",i+1);
getch();
exit(0);
}
}
printf("The Number doesn't exist");
getch();
}
}
Output/Conclusion:
enter the no of elements to be entered 6
number 1 10
number 2 20
number 3 30
number 4 40
number 5 50
number 6 60
Program Name:
This type of searching an element in the given array, the array should have elements in
sorted manner. Each time the given element is compared with the middle element of given
sorted array. And then it is decided to divide the further the given array.
Implementation:
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<stdlib.h>
void main()
{
int i,temp,ser,a[100],opt,beg=0,mid,end;
clrscr();
printf("enter the no of elements to be entered");
scanf("%d",&temp);
for(i=0;i<temp;i++)
{
printf("\n number %d ",i+1);
scanf("%d",&a[i]);
}
printf("enter the no to be searched");
scanf("%d",&ser);
end=temp,mid=(beg+end)/2;
while(beg<end)
{
if(ser>a[mid])
{
beg=mid;
}
if(ser<a[mid])
{
end=mid;
}
if(ser==a[mid])
{
printf("The Number exists at location %d",mid+1);
getch();
exit(0);
}
mid=(beg+end)/2;
}
printf("The Number doesn't exist");
getch();
}
Output/Conclusion:
enter the no of elements to be entered 6
number 1 10
number 2 20
number 3 30
number 4 40
number 5 50
number 6 60
enter the no to be searched 50
The number exists at location 5
Experiment No. 2
Program Name:
Heap is a complete binary tree. When it is represented as an array for parent node located
at nth position left child and right child are located at 2n and 2n+1 th position. For maxheap
larger element is found at parent node and largest node at root node and vice versa for min
heap. For the sorting problem first of all we create max heap by heafying the given array.
then interchange the position of root node and leaf node and remove the leaf node and keep
it in an array which is our resultant sorted array.
Implementation:
# include <stdio.h>
int arr[20],n;
main()
{
int i;
printf("Enter number of elements : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter element %d : ",i+1);
scanf("%d",&arr[i]);
}
printf("Entered list is :\n");
display();
create_heap();
printf("Heap is :\n");
display();
heap_sort();
printf("Sorted list is :\n");
display();
}/*End of main()*/
display()
{ int i;
for(i=0;i<n;i++)
printf("%d ",arr[i]);
printf("\n");
}/*End of display()*/
create_heap()
{
int i;
for(i=0;i<n;i++)
insert(arr[i],i);
}/*End of create_heap()*/
heap_sort()
{
int last;
for(last=n-1; last>0; last--)
del_root(last);
}/*End of del_root*/
del_root(int last)
{
int left,right,i,temp;
i=0; /*Since every time we have to replace root with last*/
/*Exchange last element with the root */
temp=arr[i];
arr[i]=arr[last];
arr[last]=temp;
Output/Conclusion:
Theory Concept:
Implementation:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void mergesort(int [],int,int);
void merge(int [],int,int,int);
void main()
{
int a[20],p=1,r,i,j,k,q;
clrscr();
printf("Enter the number of Array elements: ");
scanf("%d",&r);
printf("Enter the array elements:");
for(j=1;j<=r;j++)
scanf("%d",&a[j]);
mergesort(a,p,j-1);
printf("Sorted Array is: ");
for(k=1;k<=r;k++)
printf("%d",a[k]);
getch();
}
void mergesort(int a[],int p,int r)
{
int q;
if(p<r)
{
q=floor((p+r)/2);
mergesort(a,p,q);
mergesort(a,q+1,r);
merge(a,p,q,r);
}
}
void merge(int a[],int p,int q, int r)
{
int L[20],R[20];
int n1,n2,i,j,k;
n1=q-p+1;
n2=r-q;
printf("\nLeft Array\n");
for(i=1;i<=n1+1;i++)
{
L[i]=a[p+i-1];
printf("%d\t",L[i]);
}
printf("\nRight Array\n");
for(j=1;j<=n2;j++)
{
R[j]=a[q+j+1];
printf("%d\t",R[j]);
}
L[n1]=10000;R[n2]=10000;
i=1;j=1;
for(k=p;k<=r;k++)
{
if(L[i]<=R[j])
{
a[k]=L[i];
i++;
}
else
{
a[k]=R[j];
j++;
}
}
}
Output/Conclusion:
Enter the number of Array elements: 5
Enter the array elements:34 12 56 95 23
Left Array
34
Right Array
12
Left Array
12 34
Right Array
56
Left Array
95
Right Array
23
Left Array
12 34 56
Right Array
23 95
Theory Concept:
In this sorting is we first find the smallest element and then exchanging it with the first
element in array. Then finding the second smallest element and then placing it on second
position in the array and so on.
Implementation:
#include<stdio.h>
#include<conio.h>
#define MAX 25
void main()
{
int array[MAX],n,i,j;
clrscr();
printf("Enter no. of elements :");
scanf("%d",&n);
printf("\nEnter data to be sorted :\n");
for(i=0;i<n;i++)
scanf("%d",&array[i]);
for(i=1;i<n-1;i++)
for(j=n;j<i+1;j--)
if(array[i]>array[j])
{
array[i]^=array[j];
array[j]^=array[i];
array[i]^=array[j];
}
printf("Sorted data is :\n");
for(i=0;i<n;i++)
printf("%d\n",array[i]);
getch();
}
/
Output/Conclusion:
OUTPUT:
Enter no. of elements :6
Theory Concept:
Let a0, ..., an-1 be the sequence to be sorted. At the beginning and after each iteration of the
algorithm the sequence consists of two parts: the first part a0, ..., ai-1 is already sorted, the second
part ai, ..., an-1 is still unsorted (i 0, ..., n).
In order to insert element ai into the sorted part, it is compared with ai-1, ai-2 etc. When an element
aj with aj ai is found, ai is inserted behind it. If no such element is found, then ai is inserted at
the beginning of the sequence.
After inserting element ai the length of the sorted part has increased by one. In the next iteration,
ai+1 is inserted into the sorted part etc. While at the beginning the sorted part consists of element
a0 only, at the end it consists of all elements a0, ..., an-1.
Implementation:
#include<stdio.h>
#include<conio.h>
#define MAX 25
void main()
{
int array[MAX],n,i,j,key;
clrscr();
printf("Enter no. of elements :");
scanf("%d",&n);
printf("\nEnter data to be sorted :\n");
for(i=0;i<n;i++)
scanf("%d",&array[i]);
for(j=1;j<n;j++)
{
i=j-1;
key=array[j];
while(i>-1&&key<array[i])
{
array[i+1]=array[i];
i=i-1;
}
array[i+1]=key;
}
printf("Sorted data is :\n");
for(i=0;i<n;i++)
printf("%d\n",array[i]);
getch();
}
/*
Output/Conclusion
Enter no. of elements :8
5 7 0 3 4 2 6 1 (0)
5 7 0 3 4 2 6 1 (0)
0 5 7 3 4 2 6 1 (2)
0 3 5 7 4 2 6 1 (2)
0 3 4 5 7 2 6 1 (2)
0 2 3 4 5 7 6 1 (4)
0 2 3 4 5 6 7 1 (1)
0 1 2 3 4 5 6 7 (6)
*On the left side the sorted part of the sequence is shown in red. For each iteration, the number of positions the
inserted element has moved is shown in brackets.
Experiment No. 6
Program Name:
It is based on divide and conquer paradigm for sorting array. It is the best practical choice for
sorting because it is remarkably efficient on average case: its expected running time is of order of
nlogn. It works well in virtual memory.
Implementation:
#include<stdio.h>
#include<conio.h>
void quicksort(int [],int , int );
int partition(int [], int ,int );
void main()
{
int a[10],i,m;
clrscr();
printf("\nenter the size of the array : ");
scanf("%d",&m);
printf("\nenter the array element : ");
for(i=0;i<m;i++)
{ scanf("%d",&a[i]);
}
quicksort(a,0,m-1);
printf("\nsorted array is : ");
for(i=0;i<m;i++)
{ printf("%d",a[i]);
}
getch();
}
void quicksort(int a[], int p, int r)
{ int q,i;
if(p<r)
{ q=partition(a,p,r);
quicksort(a,p,q-1);
quicksort(a,q+1,r);
}
}
int partition(int a[],int p, int r)
{ int x,i,j,t;
x=a[r];
i=p-1;
for(j=p;j<=(r-1);j++)
{ if(a[j]<=x)
{ i=i+1;
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
t=a[i+1];
a[i+1]=a[r];
a[r]=t;
return (i+1);
}
Output/Conclusion:
enter the size of the array: 8
sorted array is :1 2 4 5 7 8 9 10
Experiment No. 7
Program Name:
There are n items in a store. For i =1,2, . . ., n, item i has weight wi > 0 and worth vi
> 0. Thief can carry a maximum weight of W pounds in a knapsack. In this version
of a problem the items can be broken into smaller piece, so the thief may decide to
carry only a fraction xi of object i, where 0 = xi = 1. Item i contributes xiwi to the
total weight in the knapsack, and xivi to the value of the load.
In Symbol, the fraction knapsack problem can be stated as follows.
maximize nSi=1 xivi subject to constraint nSi=1 xiwi = W
It is clear that an optimal solution must fill the knapsack exactly, for otherwise we
could add a fraction of one of the remaining objects and increase the value of the
load. Thus, in an optimal solution nSi=1 xiwi = W.
Implementation:
#include <stdio.h>
void simple_fill() {
int cur_w;
float tot_v;
int i, maxi;
int used[10];
for (i = 0; i < n; ++i)
used[i] = 0; /* I have not used the ith object yet */
cur_w = W;
while (cur_w > 0) { /* while there's still room*/
/* Find the best object */
maxi = -1;
for (i = 0; i < n; ++i)
if ((used[i] == 0) &&
((maxi == -1) || ((float)v[i]/c[i] > (float)v[maxi]/c[maxi])))
maxi = i;
return 0;
}
Output/Conclusion:
Item 1 2 3
Weight 1 2 3
Profit 2 3 4
Theory Concept:
Given a complete undirected graph G= (V, E) that has nonnegative integer cost c(u, v) associated
with each edge (u, v) in E, the problem is to find a hamiltonian cycle (tour) of G with minimum
cost. A salesperson starts from the city 1 and has to visit six cities (1 through 6) and must come
back to the starting city i.e., 1. The first route (left side) 1? 4 ? 2 ? 5? 6 ? 3 ? 1 with the total length
of 62 km, is a relevant selection but is not the best solution. The second route (right side) 1 ? 2 ?
5? 4 ? 6 ? 3 ? 1 represents the much better solution as the total distance, 48 km, is less than for the
first route.
Implementation:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
// evaluates a route
int evaluateRoute(int currentRoute[20], const int profitMatrix[20][20]);
int main()
{
// variables used
int profitMatrix[20][20];
int currentRoute[20];
int bestRoute[20];
int value=0;
int max=0;
int i=0;
long int start;
int kount=0;
return 0;
}
// tryRoute - tries a route. You get to pick what route to try next.
//
// inputs - currentRoute - the current route plan
// - bestRoute - the best route so far
// - profitMatrix - the matrix used to calculate the profit for a route
//
// outputs - currentRoute - update this plan for you current route
// - bestRoute - Update this plan for the best route you have seen.
// - profitMatrix - Changes to profitMatrix ARE NOT ALLOWED
void tryRoute(int currentRoute[20], int bestRoute[20], const int profitMatrix[20][20])
{
// variables
int planRoute[20];
int i;
int first;
int second;
static long int tries=0; // inializes to zero the first time only. (static)
// 90% of the time start over, otherwise see if we can plan a better route
// based on the current route.
if (rand() < 32767*.90)
{
// random route
createRoute(planRoute);
}
else
{
numb=rand()%10+5;
for (i=1; i<=numb; i++)
{
first=rand()%19+1;
second=rand()%19+1;
swap(route[first],route[second]);
}
}
Theory Concept:
Consider a directed graph, G(N,A), where N and A are the set of nodes and arcs, respectively.
Associated with each arc (i,j) in A is a cost c(i,j). Let |N|=n and |A|=m. The problem is to find a
rooted directed spanning tree, G(N,S) where S is a subset of A such that the sum of c(i,j) for all
(i,j) in S is minimized. The rooted directed spanning tree is defined as a graph which connects,
without any cycle, all nodes with n-1 arcs, i.e., each node, except the root, has one and only one
incoming arc.
Implementation:
#include<stdio.h>
#include<conio.h>
#define MAX 10
#define TEMP 0
#define PERM 1
#define FALSE 0
#define TRUE 1
#define infinity 9999
struct node
{
int predecessor;
int dist; /*Distance from predecessor */
int status;
};
struct edge
{
int u;
int v;
};
int adj[MAX][MAX];
int n;
main()
{
int i,j;
int path[MAX];
int wt_tree,count;
struct edge tree[MAX];
create_graph();
printf("Adjacency matrix is :\n");
display();
count = maketree(tree,&wt_tree);
create_graph()
{
int i,max_edges,origin,destin,wt;
for(i=1;i<=max_edges;i++)
{
printf("Enter edge %d(0 0 to quit) : ",i);
scanf("%d %d",&origin,&destin);
if((origin==0) && (destin==0))
break;
printf("Enter weight for this edge : ");
scanf("%d",&wt);
if( origin > n || destin > n || origin<=0 || destin<=0)
{
printf("Invalid edge!\n");
i--;
}
else
{
adj[origin][destin]=wt;
adj[destin][origin]=wt;
}
}/*End of for*/
if(i {
printf("Spanning tree is not possible\n");
exit(1);
}
}/*End of create_graph()*/
display()
{
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%3d",adj[i][j]);
printf("\n");
}
}/*End of display()*/
state[current].status=PERM;
Output/Conclusion:
No. of vertices 8
Edges 1 2 3 4 5 6 7 8 9
Weight 10 25 24 18 22 12 16 14 28
minimum spanning tree have edges e1 e2 e5 e6 e7 e9
Experiment No. 10
Program Name:
Theory Concept:
In chess, a queen can move as far as she pleases, horizontally, vertically, or diagonally. A
chess board has 8 rows and 8 columns. The standard 8 by 8 Queen's problem asks how to
place 8 queens on an ordinary chess board so that none of them can hit any other in one
move.
Implementation:
// The Backtracking Algorithm for the n-Queens Problem, in C++
#include <iostream.h>
// for cin, cout
#include <iomanip.h>
// for setw
#include <stdlib.h>
// for abs
typedef int index;
class nQueens {
public:
nQueens(int n) {
this->n = n;
col = new int[n]; // array with coordinates of queens
}
~nQueens() {
delete col;
}
void start();
void finish();
void queens(index i);
bool promising(index i);
void OutputSolution();
private:
int n;
// Dimension of board
index *col;
// col[0..n-1]: col[i]=j means queen at row i, column j
// Statistics: count number of solutions and (non)promising nodes examined.
int numSolutions, numNonPromising, numPromising;
};
void nQueens::start() {
numSolutions = 0;
// initialize statistics
numNonPromising = 0;
numPromising = 0;
queens(0);
// start search for solutions
}
void nQueens::finish() {
// Display statistics
cout << "# solutions = " << numSolutions;
cout << "
# promising nodes = " << numPromising;
cout << "
# non-promising nodes = " << numNonPromising << endl;
}
// Main routine to traverse nodes of state space tree
void nQueens::queens(index i) {
// Continue only if columns 0,...,i-1 are promising.
if (promising(i-1)) {
numPromising++;
if (i==n) {
// Have a complete solution.
numSolutions++;
OutputSolution();
} else {
for (index j=0; j<n; j++) { // place queen in
col[i] = j;
// row i, column j
queens(i+1);
// and continue to next row
}
}
} else numNonPromising++;
}
// Check if a node is promising
bool nQueens::promising(index i) {
// Check if queen in row k threatens queen in row i
for (index k=0; k<i; k++)
if (col[i] == col[k] || abs(col[i]-col[k]) == i-k)
return false;
// does threaten, so not promising
return true;
// no threats, so promising
}
// Display each solution as it’s found, and statistics
void nQueens::OutputSolution() {
cout << setw(3) << numSolutions
<< " " << setw(3) << numPromising
<< " " << setw(3) << numNonPromising << " ";
for (index i=0; i<n; i++)
cout << "(" << i+1 << "," << col[i]+1 << ") ";
cout << endl;
}
int main(int argc, char *argv[]) {
int n;
cout << "n-Queens" << endl;
do {
cout << "Enter n, or 0 to quit: ";
cin >> n;
if (n>0) {
cout << " # #P #~P coordinates" << endl;
nQueens *nq = new nQueens(n);
nq->start();
nq->finish();
delete nq;
}
} while (n>0);
return 0;
Output/Conclusion:
Taking n=4
4-queens problem
A 4-queen problem is based to place
Sort a given set of n integer elements using Quick Sort method and compute its
time complexity. Run the program for varied values of n> 5000 and record the
time taken to sort. Plot a graph of the time taken versus non graph sheet. The
elements can be read from a file or can be generated using the random number
generator. Demonstrate using Java how the divide and- conquer method works
along with its time complexity analysis: worst case, average case and best case.
Theory Concept:
Implementation:
import java.util.Scanner;
class QuickSort {
comparisons += 1;
quickSort(low, j - 1);
quickSort(j + 1, high);
}
while (i < j) {
comparisons += 1;
comparisons += 2;
i = i + 1;
comparisons += 2;
j = j - 1;
if (i < j) {
comparisons += 1;
interchange (i,j);
arr[low] = arr[j];
arr[j] = pivot;
return j;
arr[i] = arr[j];
arr[j] = temp;
int n;
System.out.println("Enter n value");
n = scanner.nextInt();
System.out.println("Quick Sort");
switch (ch) {
case 1:
arr[i] = random.nextInt();
break;
case 2:
arr[i] = i + 1;
break;
quickSort(0, n - 1);
System.out.println("Sorted
Array");
Output/Conclusion:
enter the size of the array : 8
Sort a given set of n integer elements using Merge Sort method and compute its
time complexity. Run the program for varied values of n> 5000, and record the
time taken to sort. Plot a graph of the time taken versus non graph sheet. The
elements can be read from a file or can be generated using the random number
generator. Demonstrate how the divide and- conquer method works along with
its time complexity analysis: worst case, average case and best case.
Code:
import java.util.Random;
import java.util.Scanner;
int n = in.nextInt();
for(int i=0;i<n;i++)
a[i]=rand.nextInt(2000);
System.out.println(a[i]);
start=System.nanoTime();
mergesort(a,0,n-1);
end=System.nanoTime();
System.out.println(a[i]);
int mid;
mid = (low+high)/2;
static void merge(int a[], int low, int mid, int high)
b[i]=a[h];
h=h+1;
else {
b[i] = a[j];
j=j+1;
i = i+1;
b[i]=a[k];
i= i+1;
else {
for(k=h;k<=mid;k++)
b[i]=a[k];
i= i+1;
a[k] = b[k];
}
Output:
Value of n = 5100
Theory Concept:
Given weights and values of n items, put these items in a knapsack of capacity W to get the
maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and
wt[0..n-1] which represent values and weights associated with n items respectively. Also given an
integer W which represents knapsack capacity, find out the maximum value subset of val[] such
that sum of the weights of this subset is smaller than or equal to W. You cannot break an item,
either pick the complete item or don’t pick it (0-1 property).
Given the weights and values of n items, we need to put these items in a knapsack of capacity W to
get the maximum total value in the knapsack.
In the 0-1 Knapsack problem, we are not allowed to break items. We either take the whole item or
don’t take it.
Implementation:
// Greedy approach
public class FractionalKnapSack {
// function to get maximum value
private static double getMaxValue(int[] wt, int[] val,
int capacity)
{
ItemValue[] iVal = new ItemValue[wt.length];
return totalValue;
}
// Driver code
public static void main(String[] args)
{
int[] wt = { 10, 40, 20, 30 };
int[] val = { 60, 40, 100, 120 };
int capacity = 50;
// Function call
System.out.println("Maximum value we can obtain = "
+ maxValue);
}
}