Ada Manual
Ada Manual
LAB MANUAL
NAME:
USN:
SEMESTER:
VISION
MISSION
M1: To provide technical education with the aim to develop skilled professional
to tackle complex industry challenges in the rapidly changing world.
PROGRAM: 1
AIM: Design and implement C/C++ Program to find Minimum Cost Spanning
Tree of a given connected undirected graph using Kruskal's algorithm.
DEFINITION: Kruskal’s algorithm is an algorithm in graph theory that finds a
minimum spanning tree for a connected weighted graph. This means it finds a
subset of the edges that forms a tree that includes every vertex, where the total
weight of all the edges in the tree is minimized.
If the graph is not connected then it finds a minimum spanning forest. It is an
example of a greedy algorithm.
ALGORITHM: Start with an empty set A, and select at every stage the
shortest edge that has not been chosen or rejected, regardless of where this edge
is situated in graph.
• If an edge (u, v) connects two different trees, then (u, v) is added to the
set of edges of the MST, and two trees connected by an edge (u, v) are
merged into a single tree.
• On the other hand, if an edge (u, v) connects two vertices in the same tree,
then edge (u, v) is discarded.
MST_KRUSKAL (G, w)
PROGRAM CODE:
#include<stdio.h>
#define INF 999
#define MAX 100
int p[MAX], c[MAX][MAX],t[MAX][2];
int find (int v)
{
while(p[v])
v=p[v];
return v;
}
void union1(int i,int j)
{
p[j]=i;
}
void kruskal(int n)
{
int i,j,k,u,v,min,res1,res2,sum=0;
for(k=1;k<n;k++)
{
min=INF;
for(i=1;i<n-1;i++)
{
for(j=1;j<=n;j++)
{
if(i==j)continue;
if(c[i][j]<min)
{
u=find(i);
v=find(j);
if(u!=v)
{
res1=i;
res2=j;
min=c[i][j];
}
}
}
}
union1(res1, find(res2));
t[k][1] =res1;
t[k][2]=res2;
sum=sum+min;
}
printf("\nCost of spanning tree is=%d",sum);
printf("\nEdgesof spanning tree are:\n");
for(i=1;i<n;i++)
printf("%d -> %d\n",t[i][1],t[i][2]);
}
int main()
{
int i,j,n;
printf("\nEnter the n value:");
scanf("%d",&n);
for(i=1;i<=n;i++)
p[i]=0;
printf("\nEnter the graph data:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&c[i][j]);
kruskal(n);
return 0;
}
OUTPUT:
PROGRAM: 2
AIM: Design and implement C/C++ Program to find Minimum Cost Spanning
Tree of a given connected undirected graph using Prim's algorithm.
MST_PRIM (G, w, v)
1. Q ← V[G]
2. for each u in Q do
3. key [u] ← ∞
4. key [r] ← 0
5. π[r] ← NIl
6. while queue is not empty do
7. u ← EXTRACT_MIN (Q)
8. for each v in Adj[u] do
9. if v is in Q and w(u, v) < key [v]
10. then π[v] ← w(u, v)
11. key [v] ← w(u, v)
PROGRAM CODE:
#include<stdio.h>
#define INF 999
int prim(int c[10][10],int n,int s)
{
int v[10],i,j,sum=0,ver[10],d[10],min,u;
for(i=1;i<=n;i++)
{
ver[i]=s;
d[i]=c[s][i];
v[i]=0;
}
v[s]=1;
for(i=1;i<=n-1;i++)
OUTPUT:
Enter n value:3
Enter the graph data:
0 10 1
10 0 6
160
Enter the source node:1
PROGRAM: 3A
AIM: Design and implement C/C++ Program to solve All-Pairs Shortest Paths
problem using Floyd's algorithm.
ALGORITHM:
Floyd’s Algorithm
Accept no. of vertices
Call graph function to read weighted graph // w(i,j)
Set D[ ] <- weighted graph matrix // get D {d(i,j)} for k=0
// If there is a cycle in graph, abort. How to find?
Repeat for k = 1 to n
Repeat for i = 1 to n
Repeat for j = 1 to n
D[i,j] = min {D[i,j], D[i,k] + D[k,j]}
Print D
PROGRAM CODE:
#include<stdio.h>
#define INF 999
int min(int a, int b)
{
return(a<b)?a:b;
}
void floyd(int p[][10],int n)
{
int i,j,k;
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
p[i][j]=min(p[i][j],p[i][k]+p[k][j]);
}
void main()
{
OUTPUT:
PROGRAM: 3B
AIM: Design and implement C/C++ Program to find the transitive closure
using Warshall's algorithm.
ALGORITHM:
PROGRAM CODE:
#include<stdio.h>
void warsh(int p[][10],int n)
{
int i,j,k;
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
p[i][j]=p[i][j] || p[i][k] && p[k][j];
}
int main()
{
int a[10][10],n,i,j;
printf("\nEnter the n value:");
OUTPUT:
PROGRAM: 4
AIM: Design and implement C/C++ Program to find shortest paths from a
given vertex in a weighted connected graph to other vertices using Dijkstra's
algorithm.
ALGORITHM:
Dijikstra(G,s)
//Dijikstra’s algorithm for single source shortest path
//input:A weighted connected graph with non-negative weights and its vertex s
//output:The length dv of a shortest path from s to v and penultimate vertex pv
for every vertex v in V
Initialize(Q)
for every vertex v in V do
dv<-∞;Pv<-null
Insert(Q,v,dv)
Ds<-0; Decrease(Q,s,ds);VT<-ǿ
for i<- 0 to │V│-1 do
u*<-DeleteMin(Q)
VT<-VT U{u*}
For every vertex u in V-VT that is adjacent to u* do
If du*+w(u*,u)<du
du<- du*+w(u*,u); pu<-u*
Decrease(Q,u,du)
PROGRAM CODE:
#include<stdio.h>
#define INF 999
void dijkstra(int c[10][10],int n,int s,int d[10])
{
int v[10],min,u,i,j;
for(i=1;i<=n;i++)
{
d[i]=c[s][i];
v[i]=0;
}
v[s]=1;
for(i=1;i<=n;i++)
{
min=INF;
for(j=1;j<=n;j++)
if(v[j]==0 && d[j]<min)
{
min=d[j];
u=j;
}
v[u]=1;
for(j=1;j<=n;j++)
if(v[j]==0 && (d[u]+c[u][j])<d[j])
d[j]=d[u]+c[u][j];
}
}
int main()
{
int c[10][10],d[10],i,j,s,sum,n;
printf("\nEnter n value:");
scanf("%d",&n);
printf("\nEnter the graph data:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&c[i][j]);
printf("\nEnter the souce node:");
scanf("%d",&s);
dijkstra(c,n,s,d);
for(i=1;i<=n;i++)
printf("\nShortest distance from %d to %d is %d",s,i,d[i]);
return 0;
}
OUTPUT:
Enter n value:6
PROGRAM: 5
AIM: Design and implement C/C++ Program to obtain the Topological ordering
of vertices in a given digraph.
DEFINITION: Topological ordering that for every edge in the graph, the vertex
where the edge starts is listed before the edge where the edge ends.
ALGORITHM:
2. Thje order in which the vertices are deleted yields a solution to the topological
sorting.
PROGRAM CODE:
#include<stdio.h>
int temp[10],k=0;
int i,j;
for(i=1;i<=n;i++)
if(id[i]==0)
id[i]=-1;
temp[++k]=i;
for(j=1;j<=n;j++)
id[j]--;
i=0;}}}
void main()
int a[10][10],id[10],n,i,j;
scanf("%d",&n);
for(i=1;i<=n;i++)
id[i]=0;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
if(a[i][j]==1)
id[j]++;
sort(a,id,n);
if(k!=n)
else
for(i=1;i<=k;i++)
printf("%d ",temp[i]);
OUTPUT:
001100
000110
000101
000001
000001
000000
PROGRAM: 6
AIM: Design and implement C/C++ Program to solve 0/1 Knapsack problem
using Dynamic Programming method.
Each item has both a weight and a profit. The objective is to choose the set of
items that fits in the knapsack and maximizes the profit.
Given a knapsack with maximum capacity W, and a set S consisting of n items,
Each item i has some weight wi and benefit value bi (all wi , bi and W are integer
values).
ALGORITHM:
PROGRAM CODE:
#include<stdio.h>
int w[10],p[10],n;
int max(int a,int b)
{
return a>b?a:b;
}
int knap(int i,int m)
OUTPUT:
Max profit=170
PROGRAM: 7
AIM: Design and implement C/C++ Program to solve discrete Knapsack and
continuous Knapsack problems using greedy approximation method.
DEFINITION: This program first calculates the profit-to-weight ratio for each
item, then sorts the items based on this ratio in non-increasing order. It then fills
the knapsack greedily by selecting items with the highest ratio until the knapsack
is full.
If there's space left in the knapsack after selecting whole items, it adds fractional
parts of the next item. Finally, it prints the optimal solution and the solution
vector. Here's a simplified version of the C program to solve discrete Knapsack
and continuous Knapsack problems using the greedy approximation method.
PROGRAM CODE:
#include <stdio.h>
#define MAX 50
int p[MAX], w[MAX], x[MAX];
double maxprofit;
int n, m, i;
void greedyKnapsack(int n, int w[], int p[], int m) {
double ratio[MAX];
// Calculate the ratio of profit to weight for each item
for (i = 0; i < n; i++) {
ratio[i] = (double)p[i] / w[i];
}
// Sort items based on the ratio in non-increasing order
for (i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (ratio[i] < ratio[j]) {
double temp = ratio[i];
ratio[i] = ratio[j];
ratio[j] = temp;
temp2 = p[i];
p[i] = p[j];
p[j] = temp2;
}
int currentWeight = 0;
maxprofit = 0.0;
int main() {
printf("Enter the number of objects: ");
scanf("%d", &n);
greedyKnapsack(n, w, p, m);
return 0;
}
OUTPUT:
PROGRAM: 8
AIM: Design and implement C/C++ Program to find a subset of a given set S =
{sl , s2,.... ,sn} of n positive integers whose sum is equal to a given positive
integer d.
DEFINITION: An instance of the Subset Sum problem is a pair (S, t), where S
= {x1, x2,...., xn} is a set of positive integers and t (the target) is a positive
integer. The decision problem asks for a subset of S whose sum is as large as
possible, but not larger than t.
ALGORITHM:
SumOfSub (s, k, r)
//Values of x[ j ], 1 <= j < k, have been determined
//Node creation at level k taking place: also call for creation at level K+1 if
possible
// s = sum of 1 to k-1 elements and r is sum of k to n elements
//generating left child that means including k in solution
Set x[k] = 1
If (s + s[k] = d) then subset found, print solution
If (s + s[k] + s[k+1] <=d)
then SumOfSum (s + s[k], k+1, r – s[k])
//Generate right child i.e. element k absent
If (s + r - s[k] >=d) AND (s + s[k+1] )<=d
THEN { x[k]=0;
SumOfSub(s, k+1, r – s[k])
PROGRAM CODE:
#include<stdio.h>
#define MAX 10
int s[MAX],x[MAX],d;
void sumofsub(int p,int k,int r)
{
int i;
x[k]=1;
if((p+s[k])==d)
{
for(i=1;i<=k;i++)
if(x[i]==1)
printf("%d ",s[i]);
printf("\n");
}
else
if(p+s[k]+s[k+1]<=d)
sumofsub(p+s[k],k+1,r-s[k]);
if((p+r-s[k]>=d) && (p+s[k+1]<=d))
{
x[k]=0;
sumofsub(p,k+1,r-s[k]);
}
}
int main()
{
int i,n,sum=0;
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter the set in increasing order:");
for(i=1;i<=n;i++)
scanf("%d",&s[i]);
printf("\nEnter the max subset value:");
scanf("%d",&d);
for(i=1;i<=n;i++)
sum=sum+s[i];
if(sum<d || s[1]>d)
printf("\nNo subset possible");
else
sumofsub(0,1,sum);
return 0;
}
OUTPUT:
Enter the n value:9
Enter the set in increasing order:1 2 3 4 5 6 7 8 9
Enter the max subset value:9
126
135
18
234
27
36
45
9
Snapshot 2.1
Dev-C/C++ is an Integrated Development Environment (IDE) for the C and
C++ programming languages. It is designed to provide developers with a
complete set of tools to write, compile, and debug their C/C++ programs. Here is
a small explanation covering its key features and functionality. We are using C
language. It is user friendly, open source and has less complexities.
Snapshot 2.2
Step 2: Creation of Project
Click on File -> New-> Source file -> Editor will appear where we execute the
program.
Snapshot 2.3
Snapshot 2.4
Step 3: Save the project
The program code has to be saved with .c extension. Click on File -> Save As -
> filename.c (the file name has to be the name given to the project). (Refer
snapshots 2.5 and 2.6)
Snapshot 2.5
Snapshot 2.6
Step 4: Debug and Execution of the program
Click on Execute -> Compile/F9. This checks for the errors and warnings in the
program. If there are no errors in the code then after Compile, we can Run the
program or just click F10 for the output. (Refer snapshots 2.7 and 2.8)
Snapshot 2.7
Snapshot 2.8
Step 5: Creation of PNG file.
The graph plotted is displayed as a PNG image, hence we need a PNG
file.Click on File -> New -> Source File -> Now save this blank/untitled file
using “.png” extension by Clicking File -> Save As -> filename.png (Refer
Snapshot 2.0 to 2.12)
Snapshot 2.9
Snapshot 2.10
Snapshot 2.11
Snapshot 2.12
Snapshot 2.14
Snapshot 2.15
Snapshot 2.16
Snapshot 2.17
Step 8: Setting terminal as PNG
Give command gnuplot > set terminal png
Snapshot 2.18
Snapshot 2.19
Snapshot 2.20
Now give the following commans
gnuplot > set title ‘name’ (within single quotes give the graph title)
gnuplot > set xlabel ‘x’ (within single quotes give xlabel)
gnuplot > set ylabel ‘y’ (within single quotes give ylabel)
gnuplot > set grid
gnuplot > set autoscale
Snapshot 2.21
Step 11: Setting data file path
By default, the “.dat” or the data file will be located in document section.
Right click on the “filename.dat” and go to properties, there copy the filepath
along with filename.
(Refer Snapshots 2.22 and 2.23)
Snapshot 2.22
Snapshot 2.23
Snapshot 2.24
Snapshot 2.25
Snapshot 2.26
Step 14: Graph Plotted
Snapshot 2.27
PROGRAM: 9
AIM: Design and implement C/C++ Program to sort a given set of n integer
elements using Selection. 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 n. The elements can be read from a file or can be
generated using the random number generator.
ALGORITHM:
SelectionSort (A [0…n-1])
//sort a given array by select5ion sort
//input:A[0…n-1]of orderable elements
Output:Array a[0…n-1] Sorted in ascending order
for i<- 0 to n-2 do
min<-i
for j<-i+1 to n-1 do
if A[j]<A[min] min<-j
swap A[i] and A[min]
PROGRAM CODE:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
for (;;) {
printf("\n1.Plot the Graph\n2.Selection Sort\n3.Exit");
printf("\nEnter your choice\n");
scanf("%d", &iChoice);
switch (iChoice) {
case 1:
printf("\nBefore file creation\n");
fp = fopen("SelectionPlot.dat", "w");
if (fp == NULL) {
perror("Error opening file SelectionPlot.dat");
printf("Error: Unable to create SelectionPlot.dat file for
writing.\n");
exit(1);
}
printf("File created successfully\n");
printf("\nGenerating data...\n");
case 3:
exit(0);
}
}
return 0;
}
void fnSelectionSort(int arr[], int n) {
int i, j, min_idx;
for (i = 0; i < n-1; i++) {
min_idx = i;
for (j = i+1; j < n; j++) {
if (arr[j] < arr[min_idx])
min_idx = j;
}
fnSwap(&arr[min_idx], &arr[i]);
}
}
void fnGenRandInput(int X[], int n) {
int i;
srand(time(NULL));
for (i = 0; i < n; i++) {
X[i] = rand() % 10000;
}
}
void fnDispArray(int X[], int n) {
int i;
for (i = 0; i < n; i++) {
printf(" %5d \n", X[i]);
}
}
OUTPUT:
Enter your choice
1
Generating data...
Unsorted Array
7409
5636
2361
4521
7916
3406
Sorted Array
2361
3406
4521
5636
7409
7916
PROGRAM:10
AIM: Design and implement C/C++ Program to 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 n. The elements can be read from a file or can be
generated using the random number generator.
DEFINITION: Quick sort is based on the Divide and conquer approach. Quick
sort divides array according to their value. Partition is the situation where all the
elements before some position s are smaller than or equal to A[s] and all the
elements after position s are greater than or equal to A[s].
Efficiency: Cbest(n) Є Θ(nlog2n), Cworst(n) ЄΘ(n2), Cavg(n)Є1.38nlog2n.
ALGORITHM:
Quick sort (A[l….r])
// Sorts a sub array by quick sort
//Input: A sub array A[l..r] of A[0..n-1] ,defined by its left and right indices l
//and r
// Output: The sub array A[l..r] sorted in non-decreasing order
if l < r
s = Partition (A[l..r]) //s is a split position
Quick sort (A [l …s-1])
Quick sort (A [s+1…r])
Partition (A[l…r])
//Partition a sub array by using its first element as a pivot
// Input: A sub array A [l…r] of A[0…n-1] defined by its left and right indices
l and // r (l < r)
// Output: A partition of A [l…r], with the split position returned as this
function’s value
p=A[l]
i=l;
j=r+1;
repeat
delay (500);
repeat i= i+1 until A[i] >= p
repeat j=j-1 until A[J] <= p
Swap (A[i], A[j])
until I >=j
Swap (A[i], A[j]) // Undo last Swap when i>= j
Swap (A[l], A[j])
Return j
PROGRAM CODE:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
void fnGenRandInput(int [], int);
void fnDispArray(int [], int);
int fnPartition(int [], int, int);
void fnQuickSort(int [], int, int);
inline void fnSwap(int*, int*);
inline void fnSwap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
int main() {
FILE *fp;
struct timeval tv;
double dStart, dEnd;
int iaArr[500000], iNum, iPos, iKey, i, iChoice;
for (;;) {
printf("\n1.Plot the Graph\n2.QuickSort\n3.Exit");
printf("\nEnter your choice\n");
scanf("%d", &iChoice);
switch (iChoice) {
case 1:
printf("\nBefore file creation\n");
fp = fopen("QuickPlot.dat", "w");
if (fp == NULL) {
perror("Error opening file QuickPlot.dat");
printf("Error: Unable to create QuickPlot.dat file for writing.\n");
exit(1);
}
printf("File created successfully\n");
printf("\nGenerating data...\n");
for (i = 100; i < 100000; i += 100) {
fnGenRandInput(iaArr, i);
gettimeofday(&tv, NULL);
dStart = tv.tv_sec + (tv.tv_usec / 1000000.0);
fnQuickSort(iaArr, 0, i - 1);
gettimeofday(&tv, NULL);
dEnd = tv.tv_sec + (tv.tv_usec / 1000000.0);
fprintf(fp, "%d\t%lf\n", i, dEnd - dStart);
}
fclose(fp);
printf("\nData File generated and stored in file < QuickPlot.dat >.\n
Use a plotting utility\n");
break;
case 2:
printf("\nEnter the number of elements to sort\n");
scanf("%d", &iNum);
printf("\nUnsorted Array\n");
fnGenRandInput(iaArr, iNum);
fnDispArray(iaArr, iNum);
fnQuickSort(iaArr, 0, iNum - 1);
printf("\nSorted Array\n");
fnDispArray(iaArr, iNum);
break;
case 3:
exit(0);
}
}
return 0;
}
int fnPartition(int a[], int l, int r) {
int i, j, temp;
int p;
p = a[l];
i = l;
j = r + 1;
do {
do {
i++;
} while (a[i] < p);
do {
j--;
} while (a[j] > p);
fnSwap(&a[i], &a[j]);
}
while (i < j);
fnSwap(&a[i], &a[j]);
fnSwap(&a[l], &a[j]);
return j;
}
void fnQuickSort(int a[], int l, int r) {
int s;
if (l < r) {
s = fnPartition(a, l, r);
fnQuickSort(a, l, s - 1);
fnQuickSort(a, s + 1, r);
}
}
void fnGenRandInput(int X[], int n) {
int i;
srand(time(NULL));
for (i = 0; i < n; i++) {
X[i] = rand() % 10000;
}
}
void fnDispArray(int X[], int n) {
int i;
for (i = 0; i < n; i++) {
printf(" %5d \n", X[i]);
}
}
OUTPUT:
Enter your choice
1
Generating data...
Unsorted Array
6814
2738
7882
5910
1207
Sorted Array
1207
2738
5910
6814
7882
PROGRAM: 11
AIM: Design and implement C/C++ Program to 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 n. The elements can be read from a file or can be
generated using the random number generator.
DEFINITION:
Merge sort is a sort algorithm based on divide and conquer technique. It divides
the array element based on the position in the array. The concept is that we first
break the list into two smaller lists of roughly the same size, and then use merge
sort recursively on the subproblems, until they cannot subdivide anymore. Then,
we can merge by stepping through the lists in linear time. Its time efficiency is
Θ(n log n).
ALGORITHM:
Merge sort (A[0…n-1]
// Sorts array A[0..n-1] by Recursive merge sort
// Input : An array A[0..n-1] elements
// Output : Array A[0..n-1] sorted in non decreasing order
If n > 1
Copy A[0…(n/2)-1] to B[0…(n/2)-1]
Copy A[0…(n/2)-1] to C[0…(n/2)-1]
Mergesort (B[0…(n/2)-1])
Mergesort (C[0…(n/2)-1])
Merge(B,C,A)
Merge (B[0…p-1], C[0…q-1],A[0….p+q-1])
// merges two sorted arrays into one sorted array
// Input : Arrays B[0..p-1] and C[0…q-1] both sorted
// Output : Sorted array A[0…. p+q-1] of the elements of B and C
I = 0;
J = 0;
K= 0;
While I < p and j < q do
If B[i] <= C[j]
A[k]= B[I]; I= I+1;
Else
A[k] = B[i]; I=i+1
K=k+1;
If I = = p
Copy C [ j.. q-1] to A[k….p+q-1]
else
Copy B [I … p-1] to A[k …p+q-1
PROGRAM CODE:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
int main() {
FILE *fp;
struct timeval tv;
double dStart, dEnd;
int iaArr[500000], iNum, i, iChoice;
do {
printf("\n1. Plot the Graph\n2. Merge Sort\n3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &iChoice);
switch (iChoice) {
case 1:
printf("\nBefore file creation\n");
fp = fopen("MergePlot.dat", "w");
if (fp == NULL) {
perror("Error opening file MergePlot.dat");
printf("Error: Unable to create MergePlot.dat file for writing.\n");
exit(1);
}
gettimeofday(&tv, NULL);
dStart = tv.tv_sec + (tv.tv_usec / 1000000.0);
fnMergeSort(iaArr, 0, i - 1);
gettimeofday(&tv, NULL);
dEnd = tv.tv_sec + (tv.tv_usec / 1000000.0);
fclose(fp);
printf("\nData File generated and stored in file <MergePlot.dat>.\nUse
a plotting utility\n");
break;
case 2:
printf("\nEnter the number of elements to sort: ");
scanf("%d", &iNum);
printf("\nUnsorted Array:\n");
fnGenRandInput(iaArr, iNum);
fnDispArray(iaArr, iNum);
printf("\nSorting completed.\n");
break;
case 3:
printf("\nExiting the program...\n");
exit(0);
default:
printf("\nInvalid choice! Please enter a valid option.\n");
}
} while (iChoice != 3);
return 0;
}
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2) {
free(L);
free(R);
}
OUTPUT:
1. Plot the Graph
2. Merge Sort
3. Exit
Enter your choice: 1
Before file creation
File created successfully
Generating data...
Enter your choice: 2
Enter the number of elements to sort: 5
Unsorted Array:
6239 1563 9516 7839 8082
Sorted Array:
1563 6239 7839 8082 9516
Sorting completed.
PROGRAM: 12
AIM: Design and implement C/C++ Program for N Queen's problem using
Backtracking.
ALGORITHM:
/* outputs all possible acceptable positions of n queens on n x n chessboard */
// Initialize x [ ] to zero
// Set k = 1 start with first queen
Repeat for i = 1 to n // try all columns one by one for kth queen
if Place (k, i) true then
{
x(k) = i // place kth queen in column i
if (k=n) all queens placed and hence print output (x[ ])
else NQueens(K+1,n) //try for next queen
}
Place (k,i)
/* finds if kth queen in kth row can be placed in column i or not; returns true if
queen can be placed */
// x[1,2, . . . k-1] have been defined
//queens at (p, q) & (r, s) attack if |p-r| = |q-s|
Repeat for j = 1 to (k-1)
if any earlier jth queen is in ith column ( x[j]= i)
or in same diagonal ( abs(x[ j] - i) = abs( j - k) )
then kth queen cannot be placed (return false)
return true (as all positions checked and no objection)
PROGRAM CODE:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 50
void n_queens(int n)
{
int r;
int c[MAX];
c[0]=-1;
r=0;
while(r>=0)
{ c[r]++;
while(c[r]<n && !can_place(c,r))
c[r]++;
if(c[r]<n)
{ if(r==n-1)
{ display(c,n);
printf("\n\n");
}
else
{ r++;
c[r]=-1;
}
}
else
r--;
}
}
void main()
{
int n;
clrscr();
printf("\nEnter the no. of queens:");
scanf("%d",&n);
n_queens(n);
getch();
}
OUTPUT:
Enter the no. of queens:4
-Q--
---Q
Q---
--Q-
--Q-
Q---
---Q
-Q—
6) The number of arithmetic and the operations that are required to run the program
9) The complexity of three algorithms is given as: O(n), O(n2) and O(n3). Which should
execute slowest for large value of n?
All will execute in same time.
10) In quick sort, the number of partitions into which the file of size n is divided by a selected
record is 2.
The three factors contributing to the sort efficiency considerations are the efficiency in
coding, machine run time and the space requirement for running the procedure.
11) How many passes are required to sort a file of size n by bubble sort method?
N-1
12) How many number of comparisons are required in insertion sort to sort a file if the file is
sorted in reverse order?
A. N2
13) How many number of comparisons are required in insertion sort to sort a file if the file is
already sorted? N-1
14) In quick sort, the number of partitions into which the file of size n is divided by a selected
record is 2
23) A sort which compares adjacent elements in a list and switches where necessary is .
A. insertion sort
24) The correct order of the efficiency of the following sorting algorithms according to their
overall running time comparison is
bubble>selection>insertion
25) The total number of comparisons made in quick sort for sorting a file of size n, is
A. O(n log n)
31) What are important problem types? (or) Enumerate some important types of problems.
1. Sorting 2. Searching
3. Numerical problems 4. Geometric problems
5. Combinatorial Problems 6. Graph Problems
7. String processing Problems
38) Specify the algorithms used for constructing Minimum cost spanning tree.
a) Prim’s Algorithm
b) Kruskal’s Algorithm