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

DAA-Lab File

Uploaded by

Honey Badger
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)
30 views

DAA-Lab File

Uploaded by

Honey Badger
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/ 47

R.D.

ENGINEERING COLLEGE
NAAC ACCREDITED
DEPARTMENT OF COMPUTER SCIENCE
ENGINEERING & ALLIED

PRACTICAL FILE

SESSION: 2024-2025

STUDENT NAME: __________________ ROLL NO: _________________


SEMESTER: ________ BRANCH: ________________SECTION: _______
LAB NAME: __________________________ LAB CODE: ____________
R.D. ENGINEERING COLLEGE
NAAC ACCREDITED
Department of Computer Science Engineering & Allied

INDEX
Sr. No. Name of the Practical Date of Remarks
Practical
Write a program in C for Recursive Binary & Linear
1 Search.

Write a program in C for Heap Sort.


2

Write a program in C for Merge Sort.


3

Write a program in C for Selection Sort.


4

Write a program in C for Insertion Sort.


5

Write a program in C for Quick Sort.


6

Knapsack problem using Greedy Solution.


7

Perform Travelling Salesman Problem.


8

Write a program in C to find Minimum Spanning Tree


9 using Kruskal’s Algorithm

Write a program in C to implement N Queen Problem


10 using Backtracking
Sort a given set of n integer elements using Quick Sort
11 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.

Sort a given set of n integer elements using Merge Sort


12 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.

Implement, the 0/1 Knapsack problem using (a)


13 Dynamic Programming method (b) Greedy method
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING & ALLIED

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

of taking on new challenges and above all good human beings.”

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

fields to meet the demand for human resources on a global scale.

DM3.To offer sustainable quality education, training and aspiring environment.


GENERAL LABORATORY INSTRUCTIONS
1. Students are advised to come to the laboratory at least 5 minutes before (to
the starting time), those who come after 5 minutes will not be allowed into
the lab.
2. Plan your task properly much before to the commencement, come
prepared to the lab with the synopsis / program / experiment details.
3. Student should enter into the laboratory with:
• Laboratory observation notes with all the details (Problem
statement, Aim, Algorithm, Procedure, Program, Expected Output,
etc.,) filled in for the lab session.
• Laboratory Record updated up to the last session experiments and
other utensils (if any) needed in the lab.
• Proper Dress code and Identity card.

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:

Write a program in c for sequential search

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

Enter The No To Be Searched 50

Number Exists At Location 5

Program Name:

Write a program in c for binary search


Theory Concept:

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:

Write a program in c for Heap sort


Theory Concept:

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()*/

insert(int num,int loc)


{
int par;
while(loc>0)
{
par=(loc-1)/2;
if(num<=arr[par])
{
arr[loc]=num;
return;
}
arr[loc]=arr[par];
loc=par;
}/*End of while*/
arr[0]=num;
}/*End of insert()*/

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;

left=2*i+1; /*left child of root*/


right=2*i+2;/*right child of root*/

while( right < last)


{
if( arr[i]>=arr[left] && arr[i]>=arr[right] )
return;
if( arr[right]<=arr[left] )
{
temp=arr[i];
arr[i]=arr[left];
arr[left]=temp;
i=left;
}
else
{
temp=arr[i];
arr[i]=arr[right];
arr[right]=temp;
i=right;
}
left=2*i+1;
right=2*i+2;
}/*End of while*/
if( left==last-1 && arr[i]<arr[left] )/*right==last*/
{
temp=arr[i];
arr[i]=arr[left];
arr[left]=temp;
}
}/*End of del_root*/

Output/Conclusion:

enter array elements: 23 11 44 33 55


input array is: 23 11 44 33 55
heap is: 55 44 33 23 11
sorted array is: 11 23 33 44 55
Experiment No. 3
Program Name:

Write a program in c for Merge Sort

Theory Concept:

It is based on divide and conquers method. It includes


1. Divide the main problem into sub problems.
2. Solve the main problem recursively.
3. Merging the solved sub problems into main solved problem.
Suppose we have an array A with n indices ranging from A0 to An − 1. We apply merge
sort to A (A0. Ac − 1) and A (Ac..An − 1) where c is the integer part of n / 2. When the
two halves are returned, they will have been sorted. They can now be merged together to
form a sorted array. In most implementations it is stable, meaning that it preserves the input
order of equal elements in the sorted output.

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

Sorted Array is: 12 23 34 56 95


Experiment No. 4
Program Name:

Write a program in c for Selection sort

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

Enter data to be sorted :


6
1
5
2
4
3
Sorted data is :
1
2
3
4
5
6
Experiment No. 5
Program Name:

Write a program in c for Insertion Sort

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:

Write a program in C for Quick sort


Theory Concept:

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

enter the array element :7 5 4 8 9 1 2 10

sorted array is :1 2 4 5 7 8 9 10
Experiment No. 7
Program Name:

Write a program in c to Knapsack Problem using Greedy Solution


Theory Concept:

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>

int n = 5; /* The number of objects */


int c[10] = {12, 1, 2, 1, 4}; /* c[i] is the *COST* of the ith object; i.e. what
YOU PAY to take the object */
int v[10] = {4, 2, 2, 1, 10}; /* v[i] is the *VALUE* of the ith object; i.e.
what YOU GET for taking the object */
int W = 15; /* The maximum weight you can take */

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;

used[maxi] = 1; /* mark the maxi-th object as used */


cur_w -= c[maxi]; /* with the object in the bag, I can carry less */
tot_v += v[maxi];
if (cur_w >= 0)
printf("Added object %d (%d$, %dKg) completly in the bag. Space left: %d.\n",
maxi + 1, v[maxi], c[maxi], cur_w);
else {
printf("Added %d%% (%d$, %dKg) of object %d in the bag.\n", (int)((1 +
(float)cur_w/c[maxi]) * 100), v[maxi], c[maxi], maxi + 1);
tot_v -= v[maxi];
tot_v += (1 + (float)cur_w/c[maxi]) * v[maxi];
}
}

printf("Filled the bag with objects worth %.2f$.\n", tot_v);


}

int main(int argc, char *argv[]) {


simple_fill();

return 0;
}

Output/Conclusion:

Item 1 2 3
Weight 1 2 3
Profit 2 3 4

Knapsack Solution 1,1,1/3


Experiment No. 8
Program Name:

Perform Travelling Salesman Problem

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;

// creates a random profit matrix


void createProfit(int profitMatrix[20][20]);

// creates a random route


void createRoute(int currentRoute[20]);

// evaluates a route
int evaluateRoute(int currentRoute[20], const int profitMatrix[20][20]);

// trys a new route (you get to play with this function


void tryRoute(int currentRoute[20], int bestRoute[20], const int profitMatrix[20][20]);

// swap swap two items


void swap(int &item1, int &item2);

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;

// create a random environment


createRoute(currentRoute);
createRoute(bestRoute);
createProfit(profitMatrix);

// seed the rand number generator


srand(time(0));

// loop for 60 CPU seconds


start=clock();
while ((clock()-start)<60000)
{
value=evaluateRoute(currentRoute, profitMatrix);
tryRoute(currentRoute, bestRoute, profitMatrix);

// display every 10000 cycles


kount++;
if (kount > 10000)
{
kount=0;
cout << "Current = " << evaluateRoute(currentRoute,profitMatrix) << "\t"
<< " Best = " << evaluateRoute(bestRoute,profitMatrix) << "\t"
<< " Time = " << (clock()-start)/1000
<< " " << "\r";
}
}

// output the best route found in the 60 seconds alloted


cout << "\n\n";
cout << "Profit is: " << evaluateRoute(bestRoute,profitMatrix) << "\n";
for (i=1; i<=19; i++)
{
cout << bestRoute[i] << "\n";
}
cout << "\n\n";

// Grade the route - Hopefully you did great


cout << "Grade is: " << int((evaluateRoute(bestRoute,profitMatrix)-14000)*.025+60.00) << "\n";

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)

// increments the number of tries.


tries++;

// copy the current route.


for (i=1; i<=19; i++)
{
planRoute[i]=currentRoute[i];
}

// HINT: When is it best to start over?


// When is it best to try small corrections to a known good route?
// Maybe you could use the tries counter to see if you have spent
// to much time on a specific route?

// 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
{

// HINT: Do I want to try small changes or massive changes?


// To change more than two cities put the following code in a loop!

// flip two cities


first=rand()%19+1;
second=rand()%19+1;
swap(planRoute[first],planRoute[second]);
}

// HINT: Do I really want to save a bad route for further analysis?


// Maybe sometimes, maybe never?

// save the current route reguardless of whether or not it is better


for (i=1; i<=19; i++)
{
currentRoute[i]=planRoute[i];
}

// save the best one.


if (evaluateRoute(currentRoute,profitMatrix) > evaluateRoute(bestRoute,profitMatrix))
{
// reset the tries counter
tries=0;

// save current route to best route


for (i=1; i<=19; i++)
{
bestRoute[i]=currentRoute[i];
}
}
}

// evaluateRoute - evaluates a route.


//
// inputs - route - the current route plan
// - profitMatrix - the matrix used to calculate the profit for a route
//
// outputs - the profit for the route provided.
//
int evaluateRoute(int route[20], const int profitMatrix[20][20])
{
int total=0;

for (int i=1; i<=18; i++)


{
total=total+profitMatrix[route[i]][route[i+1]];
}
total=total+profitMatrix[19][1];
return total;
}

// createRoute - creates a route.


//
// inputs - route - the current route plan
// outputs - route - a random route.
void createRoute(int route[20])
{
int first;
int second;
int numb;
int i;

for (i=1; i<=19; i++)


{
route[i]=i;
}

numb=rand()%10+5;
for (i=1; i<=numb; i++)
{
first=rand()%19+1;
second=rand()%19+1;
swap(route[first],route[second]);
}
}

// createProfit - creates a random profit matrix.


//
// inputs - profitMatrix - the current profit matrix
//
// outputs - profitMatrix - a random profit matrix.
//
void createProfit(int profitMatrix[20][20])
{
for (int i=1; i<=19; i++)
{
for (int j=1; j<=19; j++)
{
profitMatrix[i][j]=rand()%800+100;
}
}
}

// swap - exchanges two items


void swap(int &item1, int &item2)
{
int temp=item1;
item1=item2;
item2=temp;
}
Output/Conclusion:
Complexity of tsp is O(n2)
Experiment No. 9
Program Name:

Write a program in c to find minimal spanning tree using Kruskal’s


algorithm.

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);

printf("Weight of spanning tree is : %d\n", wt_tree);


printf("Edges to be included in spanning tree are : \n");
for(i=1;i<=count;i++)
{
printf("%d->",tree[i].u);
printf("%d\n",tree[i].v);
}
}/*End of main()*/

create_graph()
{
int i,max_edges,origin,destin,wt;

printf("Enter number of vertices : ");


scanf("%d",&n);
max_edges=n*(n-1)/2;

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()*/

int maketree(struct edge tree[MAX],int *weight)


{
struct node state[MAX];
int i,k,min,count,current,newdist;
int m;
int u1,v1;
*weight=0;
/*Make all nodes temporary*/
for(i=1;i<=n;i++)
{
state[i].predecessor=0;
state[i].dist = infinity;
state[i].status = TEMP;
}
/*Make first node permanent*/
state[1].predecessor=0;
state[1].dist = 0;
state[1].status = PERM;

/*Start from first node*/


current=1;
count=0; /*count represents number of nodes in tree */
while( all_perm(state) != TRUE ) /*Loop till all the nodes become
PERM*/
{
for(i=1;i<=n;i++)
{
if ( adj[current][i] > 0 && state[i].status == TEMP )
{
if( adj[current][i] < state[i].dist )
{
state[i].predecessor = current;
state[i].dist = adj[current][i];
}
}
}/*End of for*/

/*Search for temporary node with minimum distance


and make it current node*/
min=infinity;
for(i=1;i<=n;i++)
{
if(state[i].status == TEMP && state[i].dist < min)
{
min = state[i].dist;
current=i;
}
}/*End of for*/

state[current].status=PERM;

/*Insert this edge(u1,v1) into the tree */


u1=state[current].predecessor;
v1=current;
count++;
tree[count].u=u1;
tree[count].v=v1;
/*Add wt on this edge to weight of tree */
*weight=*weight+adj[u1][v1];
}/*End of while*/
return (count);
}/*End of maketree()*/

/*This function returns TRUE if all nodes are permanent*/


int all_perm(struct node state[MAX] )
{
int i;
for(i=1;i<=n;i++)
if( state[i].status == TEMP )
return FALSE;
return TRUE;
}/*End of all_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:

Write a program in c to solve n-queen problems

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

1 queen placed on row 1 Column2


2 queen placed on row 2 Column4
3 queen placed on row 3 Column1
4 queen placed on row 4 Column3
Experiment No. 11
Program Name:

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 {

static int comparisons = 0;

static int[] arr;

static void quickSort(int low, int high) {

if (low < high) {

comparisons += 1;

int j = partition(low, high);

quickSort(low, j - 1);

quickSort(j + 1, high);
}

static int partition(int low, int high) {

int pivot = arr[low];

int i = low, j = high;

while (i < j) {

comparisons += 1;

while (i < high && arr[i] <= pivot) {

comparisons += 2;

i = i + 1;

while (j > low && arr[j] >= pivot) {

comparisons += 2;

j = j - 1;

if (i < j) {
comparisons += 1;

interchange (i,j);

arr[low] = arr[j];

arr[j] = pivot;

return j;

static void interchange(int i, int j) {

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

public static void main(String[] args) {

int n;

Scanner scanner = new Scanner(System.in);

System.out.println("Enter n value");

n = scanner.nextInt();

System.out.println("Quick Sort");

System.out.println("1. Best/Average Case");

System.out.println("2. Worst Case");


int ch = scanner.nextInt();

switch (ch) {

case 1:

Random random = new


Random();

for (int i = 0; i < n; i++) {

arr[i] = random.nextInt();

break;

case 2:

for (int i = 0; i < n; i++) {

arr[i] = i + 1;

break;

long start = System.nanoTime();

quickSort(0, n - 1);

long end = System.nanoTime();

System.out.println("Sorted
Array");

for (int i = 0; i < n; i++) {


System.out.println(arr[i]);

System.out.println("Time taken: "


+ (end - start));

Output/Conclusion:
enter the size of the array : 8

enter the array element :7 5 4 8 9 1 2 10

enter the smallest element to be searched 3


the smallest element is 4
Experiment No. 12
Program Name:

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;

public class MergeSort

public static void main(String[] args)

int a[]= new int[100000];

Scanner in = new Scanner(System.in);

long start, end;

System.out.print("Enter the number of elements to be sorted: ");

int n = in.nextInt();

Random rand= new Random();

for(int i=0;i<n;i++)

a[i]=rand.nextInt(2000);

System.out.println("Array elements to be sorted are:");

for(int i=0; i<n; i++)

System.out.println(a[i]);
start=System.nanoTime();

mergesort(a,0,n-1);

end=System.nanoTime();

System.out.println("\nThe sorted elements are: ");

for(int i=0; i<n; i++)

System.out.println(a[i]);

System.out.println("\nThe time taken to sort is "+(end-start)+"ns");

static void mergesort(int a[], int low, int high)

int mid;

if(low < high)

mid = (low+high)/2;

mergesort(a, low, mid);

mergesort(a, mid+1, high);

merge(a, low, mid, high);

static void merge(int a[], int low, int mid, int high)

int i, j, h, k, b[]= new int[100000];

h=low; i=low; j=mid+1;

while((h<=mid) && (j<=high))

if(a[h] < a[j])

b[i]=a[h];
h=h+1;

else {

b[i] = a[j];

j=j+1;

i = i+1;

if(h > mid)

for(k=j; k<=high; k++)

b[i]=a[k];

i= i+1;

else {

for(k=h;k<=mid;k++)

b[i]=a[k];

i= i+1;

for(k=low; k<= high; k++)

a[k] = b[k];

}
Output:
Value of n = 5100

Random 5100 numbers will be generated


Experiment No. 13
Program

Implement, the 0/1 Knapsack problem using (a) Dynamic Programming


method (b) Greedy method.

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:

/* A Naive recursive implementation


of 0-1 Knapsack problem */
#include <stdio.h>

// A utility function that returns


// maximum of two integers
int max(int a, int b) { return (a > b) ? a : b; }

// Returns the maximum value that can be


// put in a knapsack of capacity W
int knapSack(int W, int wt[], int val[], int n)
{
// Base Case
if (n == 0 || W == 0)
return 0;
// If weight of the nth item is more than
// Knapsack capacity W, then this item cannot
// be included in the optimal solution
if (wt[n - 1] > W)
return knapSack(W, wt, val, n - 1);

// Return the maximum of two cases:


// (1) nth item included
// (2) not included
else
return max(
val[n - 1]
+ knapSack(W - wt[n - 1],
wt, val, n - 1),
knapSack(W, wt, val, n - 1));
}

// Driver program to test above function


int main()
{
int val[] = { 60, 100, 120 };
int wt[] = { 10, 20, 30 };
int W = 50;
int n = sizeof(val) / sizeof(val[0]);
printf("%d", knapSack(W, wt, val, n));
return 0;
}

// Java program to solve fractional Knapsack Problem


import java.util.Arrays;
import java.util.Comparator;

// 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];

for (int i = 0; i < wt.length; i++) {


iVal[i] = new ItemValue(wt[i], val[i], i);
}
// sorting items by value;
Arrays.sort(iVal, new Comparator<ItemValue>() {
@Override
public int compare(ItemValue o1, ItemValue o2)
{
return o2.cost.compareTo(o1.cost);
}
});

double totalValue = 0d;

for (ItemValue i : iVal) {

int curWt = (int)i.wt;


int curVal = (int)i.val;

if (capacity - curWt >= 0) {


// this weight can be picked while
capacity = capacity - curWt;
totalValue += curVal;
}
else {
// item cant be picked whole
double fraction
= ((double)capacity / (double)curWt);
totalValue += (curVal * fraction);
capacity
= (int)(capacity - (curWt * fraction));
break;
}
}

return totalValue;
}

// item value class


static class ItemValue {
Double cost;
double wt, val, ind;

// item value function


public ItemValue(int wt, int val, int ind)
{
this.wt = wt;
this.val = val;
this.ind = ind;
cost = new Double((double)val / (double)wt);
}
}

// Driver code
public static void main(String[] args)
{
int[] wt = { 10, 40, 20, 30 };
int[] val = { 60, 40, 100, 120 };
int capacity = 50;

double maxValue = getMaxValue(wt, val, capacity);

// Function call
System.out.println("Maximum value we can obtain = "
+ maxValue);
}
}

You might also like