Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 51

Dewan Institute of

Management
studies
Meerut (India)
Practical of
Data Design and Algorithm
RCA 352

Submitted to Submitted By
Pawan Kumar Goyal sir Shubham
Sharma
Astt Professor 1900740149065
CONTENTS
S.NO. NAME OF THE PROGRAM DATE REMARKS

Write a program to implement the quick


1 sort.
Write a program to implement the merge
2 sort.
Wap to implement the strassen’s matrix
3 multiplication
Write a program to implement the 0-1
4 knapsack problem.
Write a program to implement the
5 fractional knapsack problem.
Write a program to implement the job
6 sequencing with deadlines while
maximizing profits.
Write a program to implement the optimal
7 merge patterns.
8 Write a program for creating minimum
spanning tree from prim's algorithm.
9 Write a Program for creating a minimum
spanning tree from Kruskal's algorithm.
10 Write a program to implement the n-
queen's problem.
11 Write a program to implement traveling
salesman problem program.
12 Write a program to implement the
insertion sort.
13 Write a program to implement heap sort.

14 Write a program to implement the bubble


sort method.
15 Write a program to implement the
sequential search.
16 Write a program to implement the binary
search [int array].
17 Wap to find the kth smallest element in
the given list of array elements.
PROGRAM: - 1
WRITE A PROGRAM TO IMPLEMENT THE QUICK SORT.

#include (stdio.h)
#include (conio.h)
#define MAXSIZE 500
voidquickSort (int elements [], int maxsize);
void sort(int elements[], int left, int right);
int elements[MAXSIZE];
int main()
{
int i, maxsize;
printf(“\nHow many elements you want to sort: “);
scanf(“%d”,&maxsize);
printf(“\nEnter the values one by one: “);
for (i = 0; i < maxsize; i++)
{
printf (“\nEnter element %i :”,i);
scanf(“%d”,&elements[i]);
}
printf(“\nArray before sorting:\n”);
for (i = 0; i < maxsize; i++)
printf(“[%i], “,elements[i]);
printf (“\n”);
quickSort(elements, maxsize);
printf(“\nArray after sorting:\n”);
for (i = 0; i < maxsize; i++)
printf(“[%i], “, elements[i]);
}
void quickSort(int elements[], int maxsize)
{
sort (elements, 0, maxsize - 1);
}
void sort (int elements[], int left, int right)
{
int pivot, l, r;
l = left;r = right;
pivot = elements[left];
while (left < right)
{
while ((elements[right] >= pivot) && (left < right))
if (left != right)
{
elements[left] = elements[right];
left++;
}
while ((elements[left] <= pivot) && (left < right))
left++;
if (left != right)
{
elements[right] = elements[left];
}
}
elements[left] = pivot;
pivot = left;left = l;right = r;
if (left < pivot)
sort(elements, left, pivot - 1);

if (right > pivot)


sort(elements, pivot + 1, right);
}
PROGRAM: - 2
WRITE APROGRAM TO IMPLEMENT THE MERGE SORT.
#include <stdio.h>
#include <stdlib.h>
#define MAXARRAY 10
void mergesort(int a[], int low, int high);
int main(void) {
int array[MAXARRAY];
int i = 0;
/* load some random values into the array */
for(i = 0; i < MAXARRAY; i++)
array[i] = rand() % 100;
/* array before mergesort */
printf("Before :");
for(i = 0; i < MAXARRAY; i++)
printf(" %d", array[i]);
printf("\n");
mergesort(array, 0, MAXARRAY - 1);
/* array after mergesort */
printf("Mergesort :");
for(i = 0; i < MAXARRAY; i++)
printf(" %d", array[i]);
printf("\n");
return 0;}
void mergesort(int a[], int low, int high) {
int i = 0;
int length = high - low + 1;
int pivot = 0; int merge1 = 0; int merge2 = 0;
int working[length];
if(low == high)
return;
pivot = (low + high) / 2;
mergesort(a, low, pivot);
mergesort(a, pivot + 1, high);
for(i = 0; i < length; i++)
working[i] = a[low + i];
merge1 = 0;
merge2 = pivot - low + 1;
for(i = 0; i < length; i++) {
if(merge2 <= high - low)
if(merge1 <= pivot - low)
if(working[merge1] > working[merge2])
a[i + low] = working[merge2++];
else a[i + low] = working[merge1++];
else a[i + low] = working[merge2++];
else a[i + low] = working[merge1++];
}
}
PROGRAM: - 3
WAP TO IMPLEMENT THE STRASSEN’S MATRIX MULTIPLICATION
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "2DArray.h"
#define GRAIN 1024
void seqMatMult(int m, int n, int p, double** A, double** B, double** C)
{
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
{
C[i][j] = 0.0;
for (int k = 0; k < p; k++)
C[i][j] += A[i][k]*B[k][j];
}
}
void matmultleaf(int mf, int ml, int nf, int nl, int pf, int pl, double **A, double **B,
double **C)
// mf, ml;
// nf, nl;
// pf, pl;
{
for (int i = mf; i < ml; i++)
for (int j = nf; j < nl; j++)
for (int k = pf; k < pl; k++)
C[i][j] += A[i][k]*B[k][j];
}
void copyQtrMatrix(double **X, int m, double **Y, int mf, int nf)
{
for (int i = 0; i < m; i++)
X[i] = &Y[mf+i][nf];
}
void AddMatBlocks(double **T, int m, int n, double **X, double **Y)
{
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
T[i][j] = X[i][j] + Y[i][j];
}
void SubMatBlocks(double **T, int m, int n, double **X, double **Y)
{
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
T[i][j] = X[i][j] - Y[i][j];
}
void strassenMMult(int mf, int ml, int nf, int nl, int pf, int pl, double **A, double **B,
double **C)
{
if ((ml-mf)*(nl-nf)*(pl-pf) < GRAIN)
matmultleaf(mf, ml, nf, nl, pf, pl, A, B, C);
else
{
int m2 = (ml-mf)/2;
int n2 = (nl-nf)/2;
int p2 = (pl-pf)/2;
double **M1 = Allocate2DArray< double >(m2, n2);
double **M2 = Allocate2DArray< double >(m2, n2);
double **M3 = Allocate2DArray< double >(m2, n2);
double **M4 = Allocate2DArray< double >(m2, n2);
double **M5 = Allocate2DArray< double >(m2, n2);
double **M6 = Allocate2DArray< double >(m2, n2);
double **M7 = Allocate2DArray< double >(m2, n2);
double **A11 = new double*[m2];
double **A12 = new double*[m2];
double **A21 = new double*[m2];
double **A22 = new double*[m2];
double **B11 = new double*[p2];
double **B12 = new double*[p2];
double **B21 = new double*[p2];
double **B22 = new double*[p2];
double **C11 = new double*[m2];
double **C12 = new double*[m2];
double **C21 = new double*[m2];
double **C22 = new double*[m2];
double **tAM1 = Allocate2DArray< double >(m2, p2);
double **tBM1 = Allocate2DArray< double >(p2, n2);
double **tAM2 = Allocate2DArray< double >(m2, p2);
double **tBM3 = Allocate2DArray< double >(p2, n2);
double **tBM4 = Allocate2DArray< double >(p2, n2);
double **tAM5 = Allocate2DArray< double >(m2, p2);
double **tAM6 = Allocate2DArray< double >(m2, p2);
double **tBM6 = Allocate2DArray< double >(p2, n2);
double **tAM7 = Allocate2DArray< double >(m2, p2);
double **tBM7 = Allocate2DArray< double >(p2, n2);
copyQtrMatrix(A11, m2, A, mf, pf);
copyQtrMatrix(A12, m2, A, mf, p2);
copyQtrMatrix(A21, m2, A, m2, pf);
copyQtrMatrix(A22, m2, A, m2, p2);
copyQtrMatrix(B11, p2, B, pf, nf);
copyQtrMatrix(B12, p2, B, pf, n2);
copyQtrMatrix(B21, p2, B, p2, nf);
copyQtrMatrix(B22, p2, B, p2, n2);
copyQtrMatrix(C11, m2, C, mf, nf);
copyQtrMatrix(C12, m2, C, mf, n2);
copyQtrMatrix(C21, m2, C, m2, nf);
copyQtrMatrix(C22, m2, C, m2, n2);
// M1 = (A11 + A22)*(B11 + B22)
AddMatBlocks(tAM1, m2, p2, A11, A22);
AddMatBlocks(tBM1, p2, n2, B11, B22);
strassenMMult(0, m2, 0, n2, 0, p2, tAM1, tBM1, M1);
//M2 = (A21 + A22)*B11
AddMatBlocks(tAM2, m2, p2, A21, A22);
strassenMMult(0, m2, 0, n2, 0, p2, tAM2, B11, M2);
//M3 = A11*(B12 - B22)
SubMatBlocks(tBM3, p2, n2, B12, B22);
strassenMMult(0, m2, 0, n2, 0, p2, A11, tBM3, M3);
//M4 = A22*(B21 - B11)
SubMatBlocks(tBM4, p2, n2, B21, B11);
strassenMMult(0, m2, 0, n2, 0, p2, A22, tBM4, M4);
//M5 = (A11 + A12)*B22
AddMatBlocks(tAM5, m2, p2, A11, A12);
strassenMMult(0, m2, 0, n2, 0, p2, tAM5, B22, M5);
//M6 = (A21 - A11)*(B11 + B12)
SubMatBlocks(tAM6, m2, p2, A21, A11);
AddMatBlocks(tBM6, p2, n2, B11, B12);
strassenMMult(0, m2, 0, n2, 0, p2, tAM6, tBM6, M6);
//M7 = (A12 - A22)*(B21 + B22)
SubMatBlocks(tAM7, m2, p2, A12, A22);
AddMatBlocks(tBM7, p2, n2, B21, B22);
strassenMMult(0, m2, 0, n2, 0, p2, tAM7, tBM7, M7);
for (int i = 0; i < m2; i++)
for (int j = 0; j < n2; j++) {
C11[i][j] = M1[i][j] + M4[i][j] - M5[i][j] + M7[i][j];
C12[i][j] = M3[i][j] + M5[i][j];
C21[i][j] = M2[i][j] + M4[i][j];
C22[i][j] = M1[i][j] - M2[i][j] + M3[i][j] + M6[i][j];
}
Free2DArray< double >(M1);
Free2DArray< double >(M2);
Free2DArray< double >(M3);
Free2DArray< double >(M4);
Free2DArray< double >(M5);
Free2DArray< double >(M6);
Free2DArray< double >(M7);
delete[] A11; delete[] A12; delete[] A21; delete[] A22;
delete[] B11; delete[] B12; delete[] B21; delete[] B22;
delete[] C11; delete[] C12; delete[] C21; delete[] C22;
Free2DArray< double >(tAM1);
Free2DArray< double >(tBM1);
Free2DArray< double >(tAM2);
Free2DArray< double >(tBM3);
Free2DArray< double >(tBM4);
Free2DArray< double >(tAM5);
Free2DArray< double >(tAM6);
Free2DArray< double >(tBM6);
Free2DArray< double >(tAM7);
Free2DArray< double >(tBM7);
}
}
void matmultS(int m, int n, int p, double **A, double **B, double **C)
{
int i,j;
for (i=0; i < m; i++)
for (j=0; j < n; j++)
C[i][j] = 0;
strassenMMult(0, m, 0, n, 0, p, A, B, C);
}
int CheckResults(int m, int n, double **C, double **C1)
{
#define THRESHOLD 0.001
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (abs(C[i][j] - C1[i][j]) > THRESHOLD )
{
printf("%f %f\n", C[i][j], C1[i][j]);
return 1;
}
}
}
return 0;
}
int main(int argc, char* argv[])
{
clock_t before, after;

int M = atoi(argv[1]);
int N = atoi(argv[2]);
int P = atoi(argv[3]);

double **A = Allocate2DArray< double >(M, P);


double **B = Allocate2DArray< double >(P, N);
double **C = Allocate2DArray< double >(M, N);
double **C4 = Allocate2DArray< double >(M, N);

int i, j;

for (i = 0; i < M; i++)


{
for (j = 0; j < P; j++)
{
A[i][j] = 5.0 - ((double)(rand()%100) / 10.0);
}
}
for (i = 0; i < P; i++)
{
for (j = 0; j < N; j++)
{
B[i][j] = 5.0 - ((double)(rand()%100) / 10.0);
}
}
printf("Execute Standard matmult\n\n");
before = clock();
seqMatMult(M, N, P, A, B, C);
after = clock();
printf("Standard matrix function done in %7.2f secs\n\n\n",(float)(after - before)/
CLOCKS_PER_SEC);
before = clock();
matmultS(M, N, P, A, B, C4);
after = clock();
printf("Strassen matrix function done in %7.2f secs\n\n\n",(float)(after - before)/
CLOCKS_PER_SEC);
if (CheckResults(M, N, C, C4))
printf("Error in matmultS\n\n");
else
printf("OKAY\n\n");
Free2DArray(A);
Free2DArray(B);
Free2DArray(C);
Free2DArray(C4);
return 0;
}

PROGRAM: - 4
WRITE APROGRAM TO IMPLEMENT THE 0-1 KNAPSACK PROBLEM.
#include <stdio.h>
#define MAXWEIGHT 100

intn=3;
intc[10]={8,6,4};
intv[10]={16,10,7};
intW=10;
voidfill_sack()
{
inta[MAXWEIGHT];
intlast_added[MAXWEIGHT];
inti,j;
intaux;
for(i=0;i<=W;++i)
{
a[i]=0;
last_added[i]=-1;
}
a[0]=0;
for(i=1;i<=W;++i)
for(j=0;j<n;++j)
if((c[j]<=i)&&(a[i]<a[i-c[j]]+v[j]))
{
a[i]=a[i-c[j]]+v[j];
last_added[i]=j;
}
for(i=0;i<=W;++i)
if(last_added[i]!=-1)
printf("Weight %d; Benefit: %d; To reach this weight I added object %d (%d$ %dKg) to
weight %d.\n",i,a[i],last_added[i]+1,v[last_added[i]],c[last_added[i]],i-c[last_added[i]]);
else
printf("Weight %d; Benefit: 0; Can't reach this exact weight.\n",i);
printf("---\n");
aux=W;
while((aux>0)&&(last_added[aux]!=-1)){
printf("Added object %d (%d$ %dKg). Space left: %d\n",last_added[aux]
+1,v[last_added[aux]],c[last_added[aux]],aux-c[last_added[aux]]);
aux-=c[last_added[aux]];
}

printf("Total value added: %d$\n",a[W]);


}
intmain(intargc,char*argv[])
{
fill_sack();
return0;
}
PROGRAM: - 5
WRITE APROGRAM TO IMPLEMENT THE FRACTIONAL KNAPSACK PROBLEM.
#include <stdio.h>
intn=5;
intc[10]={12,1,2,1,4};
intv[10]={4,2,2,1,10};
intW=15;
voidsimple_fill()
{
intcur_w;
floattot_v;
inti,maxi;
intused[10];
for(i=0;i<n;++i)
used[i]=0;
cur_w=W;
while(cur_w>0)
{
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;
cur_w-=c[maxi];
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);
}
intmain(intargc,char*argv[])
{
simple_fill();
return0;
}
PROGRAM: - 6
WRITE APROGRAM TO IMPLEMENT THE JOB SEQUENCING WITH DEADLINES
WHILE MAXIMIZING PROFITS.

#include<iostream>
#include<list>
using namespace std;
class node
{
public:
int d,p,t;
bool operator < (node n)
{
if(p<n.p)
return 1;
else
return 0;
}
};
int main()
{int d,p,t,i,profit,min,n;
list<node> lst;
node pt;
cout<<"Enter no of entries";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"enter data(p,d,t)";
cin>>p>>d>>t;
pt.d=d;pt.p=p;pt.t=t;
lst.push_back(pt);
}
int maxd=0;
lst.sort();
lst.reverse();
cout<<"sorted list";
list<node> :: iterator itr=lst.begin();
while(itr!=lst.end())
{
pt=*itr;
if(maxd<pt.d) maxd=pt.d;
cout<<pt.p<<endl<<pt.d<<endl<<pt.t<<endl<<endl;
itr++;
}
//cout<<" max deadline "<<maxd<<endl;
itr=lst.begin();
profit=0;
while(itr!=lst.end())
{
pt=*itr;
if(pt.d>=pt.t)
min=pt.t;
elsemin=pt.d;
if(maxd>=min)
profit+=min*pt.p;
else
profit+=maxd*pt.p;
itr++;maxd=maxd-min;
}
cout<<"profit is : "<<profit<<endl;
return 0;
}

PROGRAM: - 7
WRITE APROGRAM TO IMPLEMENT THE OPTIMAL MERGE PATTERNS.

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i,k,a[10],c[10],n,l;
cout<<"Enter the no. of elements\t";
cin>>n;
cout<<"\nEnter the sorted elments for optimal merge pattern";
for(i=0;i<n;i++)
{
cout<<"\t";
cin>>a[i];
}
i=0;k=0;
c[k]=a[i]+a[i+1];
i=2;
while(i<n)
{
k++;
if((c[k-1]+a[i])<=(a[i]+a[i+1]))
{
c[k]=c[k-1]+a[i];
}
else
{
c[k]=a[i]+a[i+1];
i=i+2;
while(i<n)
{ k++;
if((c[k-1]+a[i])<=(c[k-2]+a[i]))
{
c[k]=c[k-1]+a[i];
}
else
{
c[k]=c[k-2]+a[i];
}i++;
}
}i++;
}
k++;
c[k]=c[k-1]+c[k-2];
cout<<"\n\nThe optimal sum are as follows......\n\n";
for(k=0;k<n-1;k++)
{
cout<<c[k]<<"\t";
}
l=0;
for(k=0;k<n-1;k++)
{
l=l+c[k];
}
cout<<"\n\n The external path length is ......"<<l;
getch();
}

PROGRAM: - 8
WRITE APROGRAM FOR CREATING MINIMUM SPANNING TREE FROM
PRIM'SALGORITHM.
#include<stdio.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;
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);
}
}
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;
}
}
if(i
{
printf("Spanning tree is not possible\n");
exit(1);
}
}
display()
{
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%3d",adj[i][j]);
printf("\n");
}
}

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;
for(i=1;i<=n;i++)
{
state[i].predecessor=0;
state[i].dist = infinity;
state[i].status = TEMP;
}
state[1].predecessor=0;
state[1].dist = 0;
state[1].status = PERM;

current=1;
count=0;
while( all_perm(state) != TRUE )
{
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];
}
}
}
min=infinity;
for(i=1;i<=n;i++)
{
if(state[i].status == TEMP && state[i].dist < min)
{
min = state[i].dist;
current=i;
}
}
state[current].status=PERM;
u1=state[current].predecessor;
v1=current;
count++;
tree[count].u=u1;
tree[count].v=v1;
*weight=*weight+adj[u1][v1];
}
return (count);
}
int all_perm(struct node state[MAX] )
{
int i;
for(i=1;i<=n;i++)
if( state[i].status == TEMP )
return FALSE;
return TRUE;
}
PROGRAM: - 9
Write a Program for creating a minimum spanning tree from
Kruskal'salgorithm.
#include
#define MAX 20
struct edge
{
int u;
int v;
int weight;
struct edge *link;
}
*front = NULL;
int father[MAX];
struct edge tree[MAX];
int n;
int wt_tree=0;
int count=0;

void make_tree();
void insert_tree(int i,int j,int wt);
void insert_pque(int i,int j,int wt);
struct edge *del_pque();

main()
{
int i;

create_graph();
make_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);
}
printf("Weight of this minimum spanning tree is : %d\n", wt_tree);
}

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

printf("Enter number of nodes : ");


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
insert_pque(origin,destin,wt);
}
if(i
{
printf("Spanning tree is not possible\n");
exit(1);
}
}

void make_tree()
{
struct edge *tmp;
int node1,node2,root_n1,root_n2;
while( count < n-1)
{
tmp=del_pque();
node1=tmp->u;
node2=tmp->v;

printf("n1=%d ",node1);
printf("n2=%d ",node2);

while( node1 > 0)


{
root_n1=node1;
node1=father[node1];
}
while( node2 >0 )
{
root_n2=node2;
node2=father[node2];
}
printf("rootn1=%d ",root_n1);
printf("rootn2=%d\n",root_n2);

if(root_n1!=root_n2)
{
insert_tree(tmp->u,tmp->v,tmp->weight);
wt_tree=wt_tree+tmp->weight;
father[root_n2]=root_n1;
}
}
}
void insert_tree(int i,int j,int wt)
{
printf("This edge inserted in the spanning tree\n");
count++;
tree[count].u=i;
tree[count].v=j;
tree[count].weight=wt;
}
void insert_pque(int i,int j,int wt)
{
struct edge *tmp,*q;

tmp = (struct edge *)malloc(sizeof(struct edge));


tmp->u=i;
tmp->v=j;
tmp->weight = wt;

if( front == NULL || tmp->weight < front->weight )


{
tmp->link = front;
front = tmp;
}
else
{
q = front;
while( q->link != NULL && q->link->weight <= tmp->weight )
q=q->link;
tmp->link = q->link;
q->link = tmp;
if(q->link == NULL)
tmp->link = NULL;
}
}
struct edge *del_pque()
{
struct edge *tmp;
tmp = front;
printf("Edge processed is %d->%d %d\n",tmp->u,tmp->v,tmp->weight);
front = front->link;
return tmp;
}

PROGRAM: - 10
WRITE APROGRAM TO IMPLEMENT THE N-QUEEN'S PROBLEM.

#include <iostream.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
void check(int, int, char [100][100]);
void print(char [100][100]);
int no_of_queens, queen = 2, flagrow = 0, flagcol = 0;
int count = 1;
char ch, response_row, response_col;
int main(void)
{
int row, col, i;
char board[100][100], response;
clrscr ();
Printf ("@@ This is n-queen problem.Enter the number ofqueens (say n) and watch how
computer places them in (n x n) matrixsuch that none can meet another moving along
horizontally, verticallyor digonally.");
printf("Enter the number of queens : ");
scanf("%d", &no_of_queens);
if(no_of_queens > 23)
{
Printf (" @@ Thought the program is OK for any queen value. Butdue the configuration
of the output screen the output will betranketed (A very large queen number may cause
the system stackoverflow).So it is highly recommended that you run the program
withmaximum queen number 23...");
printf("Want to continue(Y/N)?");
fflush(stdin);
scanf("%c", &response);
if(toupper(response) == 'N')
return (0);
}
else if(no_of_queens < 3)
{
printf("The number of Queen must be greater than 3.");
getch();
return (0);
}
printf("Want a row number below the board(Y/N) : ");
fflush(stdin);
response_row = (char)getchar();
if(toupper(response_row) == 'Y')
flagrow = 1;
printf("Want a column number below the board(Y/N) : ");
fflush(stdin);
response_col = (char)getchar();
if(toupper(response_col) == 'Y')
flagcol = 1;
clrscr();
printf("M/c in work ! Please Wait...");

// This for-loop is used for checking all the columns of row 0 only...
setcursortype(_NOCURSOR);
for(col = 0; col < no_of_queens; col++)
{
memset(board, '-', sizeof(board));
check( 0, col, board );
}
clrscr();
printf("Thank you for seeing this program through.");
getch();
return (0);
}

void check( int r, int c, char board[100][100] )


{
int i, j;

// Terminating condition for the recursion...


if ( ( r == no_of_queens ) && ( c == 0 ))
{
clrscr();
printf(" (%d-Queen) Set : %d", no_of_queens, count++);
print( board );
fflush(stdin);
ch = (char)getch();
clrscr();
if(ch == 'e')
exit (0);
printf("M/c in work ! Please Wait...");
}

// Vertical check...
for(i = 0; i < r; i++)
{
if ( board[i][c] == queen)
return;
}

// Horizontal check...
for(j = 0; j < c; j++)
{
if ( board[r][j] == queen)
return;
}

// Left-Diagonal check...
i = r; j = c;
do
{
if ( board[i][j] == queen )
return;
i--; j--;
}
while( i >= 0 && j >= 0 );

// Right-Diagonal check...
i = r; j = c;
do
{
if ( board[i][j] == queen )
return;
i--; j++;
}
while( i >= 0 && j < no_of_queens );

// Placing the queen if the ckecked position is OK...


board[r][c] = queen;
r++;

// This for-loop is used for checking all the columns for each row
//starting from 1 upto the end...
for(int p = 0; p < no_of_queens; p++)
check(r, p, board);
for(int h = 0; h < no_of_queens; h++)
board[r - 1][h] = '-';

void print(char board[100][100])


{

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


{
if(flagrow == 1)
printf("%3d", i + 1);

for(int j = 0; j < no_of_queens; j++)


{
if(board[i][j] == queen)
{
textcolor(RED);
cprintf("%3c", queen);
}
else
{
textcolor(8); //dark gray
cprintf("%3c", 22);
}
}
printf("");
}
textcolor(7);
if(flagcol == 1)
{
if(flagrow)
printf(" ");
for(i = 0; i < no_of_queens; i++)
printf("%3d", i + 1);
}
gotoxy(62, 1);
printf("Press E to exit.");
textcolor(7);
}
PROGRAM: - 11
WRITE APROGRAM TO IMPLEMENT TRAVELING SALESMAN PROBLEM
PROGRAM.

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
void createProfit(int profitMatrix[20][20]);
void createRoute(int currentRoute[20]);
int evaluateRoute(int currentRoute[20], const int profitMatrix[20][20]);
void tryRoute(int currentRoute[20], int bestRoute[20], const int profitMatrix[20][20]);
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;
}

PROGRAM: - 12
WRITE APROGRAM TO IMPLEMENT THE INSERTION SORT.

#include<stdio.h>
void main()
{
int A[20], N, Temp, i, j;
clrscr();
printf("\n\n\t ENTER THE NUMBER OF TERMS...: ");
scanf("%d", &N);
printf("\n\t ENTER THE ELEMENTS OF THE ARRAY...:");
for(i=0; i<N; i++)
{
gotoxy(25,11+i);
scanf("\n\t\t%d", &A[i]);
}
for(i=1; i<N; i++)
{
Temp = A[i];
j = i-1;
while(Temp<A[j] && j>=0)
{
A[j+1] = A[j];
j = j-1;
}
A[j+1] = Temp;
}
printf("\n\tTHE ASCENDING ORDER LIST IS...:\n");
for(i=0; i<N; i++)
printf("\n\t\t\t%d", A[i]);
getch();
PROGRAM: - 13

WRITE APROGRAM TO IMPLEMENT HEAP SORT.

#include<stdio.h>
void restoreHup(int*,int);
void restoreHdown(int*,int,int);
void main()
{
int a[20],n,i,j,k;
printf("
Enter the number of elements to sort : ");
scanf("%d",&n);
printf("
Enter the elements :
");
for(i=1;i<=n;i++){
scanf("%d",&a[i]);
restoreHup(a,i);
}
j=n;
for(i=1;i<=j;i++)
{
int temp;
temp=a[1];
a[1]=a[n];
a[n]=temp;
n--;
restoreHdown(a,1,n);
}

n=j;

printf("
Here is it...
");
for(i=1;i<=n;i++)
printf("%4d",a[i]);
}

void restoreHup(int *a,int i)


{
int v=a[i];

while((i>1)&&(a[i/2]<v))
{
a[i]=a[i/2];
i=i/2;
}
a[i]=v;
}

void restoreHdown(int *a,int i,int n)


{
int v=a[i];
int j=i*2;
while(j<=n)
{
if((j<n)&&(a[j]<a[j+1]))
j++;
if(a[j]<a[j/2]) break;

a[j/2]=a[j];
j=j*2;
}
a[j/2]=v;
}
PROGRAM: - 14
WRITE APROGRAM TO IMPLEMENT THE BUBBLE SORT METHOD.

#include<stdio.h>
#include<conio.h>
main()
{ int arr[50],temp,i,j,n;
clrscr();
printf("\nEnter any Value less Than 50");
scanf("%d",&n);
printf("\n\tEnter The Values into ARRAY ");
for(i=0;i<n;i++)
{ printf("\n\n Enter Element no %d: ",i+1);
scanf("%d",&arr[i]);
}
for(i=0;i<n-1;i++)
{for(j=0;j<n-i-1;j++)
{ if(arr[j] >arr[j+1])
{ temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}}}
printf("\n\n-- Sorted Series --");
for(i=0;i<n;i++)
{
printf("\n \n \t %d",arr[i]);
}
getch();
}

PROGRAM: - 15
WRITE APROGRAM TO IMPLEMENT THE SEQUENTIAL SEARCH.

#include <stdio.h>
#define MAX 24
void createIndex(int index[],int isize,int arr[],int asize)
{     
int i,j;
   for(i=0,j=0;i<asize;i+=8,j++)
{  
ndex[j]= arr[i];        
}
   index[j] = arr[asize-1]; }
int indexSeqSearch(int val, int index[], int isize, int arr[], int asize)
{    
int i=0,j=0,pos=0;
   int high=0,low=0;
 
   if(val > index[isize-1] && val < index[0])
    return -1; 
    while(i<isize)
   {                
if(val == index[i])
  {     
pos = 8 * i;
     return pos;
     } 
if(val < index[i])
   {  
low = 8 * (i-1);                                            
high = 8 * i;
     break;                
}
  else      
{
  low = 8 * i;
   high = 8 * (i+1);
}         
i++;
  }       
while(low < high)
{        
if(val == arr[low])
   return low;
   else
  low++;
   }
   return -1;
}
 int main()
{
int arr[MAX]={ 8,14,26,38,72,115,306,
                321,329,387,409,512,540,567,583,592,602,611,618,741,798,811,814,876};
 int index[(MAX/8)+1]={0};
 createIndex(&index[0],(MAX/8)+1,&arr[0],MAX);
  int opt=0,pos=0;
  while(opt < MAX)
{
  pos = indexSeqSearch(arr[opt],&index[0],(MAX/8)+1,&arr[0],MAX);
  if( pos != -1)
 {
 printf("\n%d found at position %d",arr[opt],pos);               

else  
printf("\n%d not found.",arr[opt]);
  opt++;
    }  
        return 0;
}

PROGRAM: - 16
WRITE APROGRAM TO IMPLEMENT THE BINARY SEARCH [INT ARRAY].

#include <stdio.h>
#define TRUE 0
#define FALSE 1

int main (void)


{
 int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 int left = 0;
 int right = 10;
 int middle = 0;
 int number = 0;
 int bsearch = FALSE;
 int i = 0;
 printf("ARRAY: ");
 for(i = 1; i <= 10; i++)
 printf("[%d] ", i);
 printf("\nSearch for Number: ");
 scanf("%d", &number);
 while(bsearch == FALSE && left <= right)
{
  middle = (left + right) / 2;
if(number == array[middle])
{
   bsearch = TRUE;
   printf("** Number Found **\n");
 }
else
{
  if(number < array[middle]) right = middle - 1;
   if(number > array[middle]) left = middle + 1;
 }
 }
 if(bsearch == FALSE)
  printf("-- Number Not found --\n");
 return 0;
}

PROGRAM: - 17
WAP TO FIND THE kth SMALLEST ELEMENT IN THE GIVEN LIST OF ARRAY
ELEMENTS.

#include <stdio.h>
#include<conio.h>
main ()
{
int a[20], i,n;
printf ("ent how many elements u want to enter");
scanf ("%d",&n);
printf ("enter the elements");
for (i=1;i<=n;i++)
scanf ("%d",&a[i]));
s=a [1];
for (i=2;i<=n;i++)
{
if
{
s>a[i]
s=a[i]
}
}
Printf ("the smallest element is %d",s);
}

You might also like