Design & Analysis of Algorithms
Lab
Lab No 1:
Q) Implementation and Analysis of Sorting Algorithms – Quick Sort,
Merge Sort & Heap Sort.
Quick Sort:
Algorithm:
Step 1 - Choose the highest index value has pivot.
Step 2 - Take two variables to point left and right of the list excluding pivot.
Step 3 - left points to the low index.
Step 4 - right points to the high.
Step 5 - while value at left is less than pivot move right.
Step 6 - while value at right is greater than pivot move left.
Step 7 - if both step 5 and step 6 does not match swap left and right.
Step 8 - if left ≥ right, the point where they met is new pivot
CODE:
#include<stdio.h>
int partition (int a[], int start, int end)
{
int pivot = a[end];
int i = (start - 1);
for (int j = start; j <= end - 1; j++)
{
if (a[j] < pivot)
{
i++;
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
int t = a[i+1];
a[i+1] = a[end];
a[end] = t;
return (i + 1);
}
void quick(int a[], int start, int end)
{
if (start < end)
{
int p = partition(a, start, end);
quick(a, start, p - 1);
quick(a, p + 1, end);
}
}
void printArr(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
{
Merge sort:
Algorithm:
Step 1 - if it is only one element in the list it is already sorted, return.
Step 2 - divide the list recursively into two halves until it can no more be divided.
Step 3 - merge the smaller lists into new list in sorted order.
Code:
#include <stdio.h>
void merge(int a[], int beg, int mid, int end)
{
int i, j, k;
int n1 =mid - beg + 1;
int n2 = end - mid;
int LeftArray[n1],RightArray[n2];
for (int i = 0; i< n1; i++)
LeftArray[i] =a[beg + i];
for (int j = 0; j < n2;j++)
RightArray[j] = a[mid + 1 + j];
i =0;
j =0;
k= beg;
while (i < n1 && j < n2)
{
if(LeftArray[i] <= RightArray[j])
{
a[k] = LeftArray[i];
i++;
}
else
{
a[k] = RightArray[j];
j++;
}
k++;
}
while (i<n1)
{
a[k] = LeftArray[i];
i++;
k++;
}
while (j<n2){
a[k] = RightArray[j];
j++;
k++;
}
}
void mergeSort(int a[], int beg, int end)
{
if (beg < end)
{
int mid = (beg + end) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
merge(a, beg, mid, end);
}
}
void printArray(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}
int main() {
int a[] = { 14,3,455,34,5,69 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArray(a, n);
mergeSort(a, 0, n - 1);
printf("After sorting array elements are - \n");
printArray(a, n);
return 0;
}
Output:
Heap sort:
Algorithm:
Step 1 - Create a new node at the end of heap.
Step 2 - Assign new value to the node.
Step 3 - Compare the value of this child node with its parent.
Step 4 - If value of parent is less than child, then swap them.
Step 5 – Repeat step 3 & 4 until Heap property holds.
Code:
#include <stdio.h>
void heapify(int a[], int n, int i)
{
int largest = i;
int left = 2 *
i + 1;
int right = 2 * i + 2;
if(left < n && a[left] > a[largest])
largest = left;
if (right < n && a[right] > a[largest])
largest =right;
if (largest != i) {
int temp = a[i];
a[i] = a[largest];
a[largest] = temp;
heapify(a, n, largest);
}
}
void heapSort(int a[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(a, n, i);
for (int i = n- 1; i >= 0; i--) {
int temp= a[0];
a[0] = a[i];
a[i] = temp;
heapify(a, i, 0);
}
}
void printArr(int arr[], int n)
{
for (int i = 0; i < n; ++i)
{
printf("%d",arr[i]);
printf(" ");
}
}
int main()
{
int a[] = {89, 232, 433, 284, 278, 155};
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are -\n");
printArr(a, n);
heapSort(a, n);
printf(“\nAfter sorting array elements are -\n);
printArr(a,n);
return 0;
}
Output:
Lab No 2:
Q)Warshalls Algorithms – Applying to Topological Ordering of vertices in
a given digraph and computing the transitive closure of given directed
graph.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<math.h>
int max(int,int);
void warshal(int p[10][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]=max(p[i][j],p[i][k]&&p[k][j]);
}
int max(int a,int b)
{
if(a>b)
return(a);
else
return(b);
}
void main() {
int p[10][10]= {0},n,e,u,v,i,j;
printf("\n Enter the number of vertices:");
scanf("%d",&n);printf("\n Enter the number of edges:");
scanf("%d",&e);
for (i=1;i<=e;i++) {
printf("\n Enter the end vertices of edge %d:",i);
scanf("%d%d",&u,&v);
p[u][v]=1;
}
printf("\n Matrix of input data: \n");
for (i=1;i<=n;i++) {
for (j=1;j<=n;j++)
printf("%d\t",p[i][j]);
printf("\n");
}
warshal(p,n);
printf("\n Transitive closure: \n");
for (i=1;i<=n;i++) {
for (j=1;j<=n;j++)
printf("%d\t",p[i][j]);
printf("\n");
}
getch();
}
OUTPUT:
Lab No 3:
Q)Implement 0/1 Knapsack Problem using Dynamic Programming.
CODE:
#includ
#include<stdio.h>
int max(int a, int b)
{
if(a>b)
{
return a;
}
else
{
return b;
}
}
int knapsack(int W, int wt[], int val[], int n)
{
int i, w;
int knap[n+1][W+1];
for (i = 0; i <= n; i++)
{
for (w = 0; w <= W; w++)
{
if (i==0 || w==0)
knap[i][w] = 0;
else if (wt[i-1] <= w)
knap[i][w] = max(val[i-1] + knap[i-1][w-wt[i-1]], knap[i-1][w]);
else
knap[i][w] = knap[i-1][w];
}
}
return knap[n][W];
}
int main()
{
int val[] = {20, 25, 40};
int wt[] = {25, 20, 30};
int W = 50;
int n = sizeof(val)/sizeof(val[0]);
printf("The solution is : %d", knapsack(W, wt, val, n));
return 0;
}
OUTPUT:
The solution is : 65
Lab No 4:
Q)Shortest Paths Algorithms : All Pair Shortest Path algorithms – Floyds
Algorithm and other algorithms.
CODE:
#include<stdio.h>
int min(int,int);
void floyds(int p[10][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++)
if(i==j)
p[i][j]=0;
else
p[i][j]=min(p[i][j],p[i][k]+p[k][j]);
}
int min(int a,int b)
{
if(a<b)
return(a);
else
return(b);
}
void main()
{
int p[10][10],w,n,e,u,v,i,j;;
printf("\n Enter the number of vertices:");
scanf("%d",&n);
printf("\n Enter the number of edges:\n");
scanf("%d",&e);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
p[i][j]=999;
}
for(i=1;i<=e;i++)
{
printf("\n Enter the end vertices of edge%d with its weight \n",i);
scanf("%d%d%d",&u,&v,&w);
p[u][v]=w;
}
printf("\n Matrix of input data:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d \t",p[i][j]);
printf("\n");
}
floyds(p,n);
printf("\n Transitive closure:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d \t",p[i][j]);
printf("\n");
}
printf("\n The shortest paths are:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(i!=j)
printf("\n <%d,%d>=%d",i,j,p[i][j]);
}
}
Lab No 5:
Q)Implement any scheme to find the optimal solution for the Travelling
Salesman Problem.
CODE:
#include<stdio.h>
int ary[10][10],completed[10],n,cost=0;
void takeInput()
{
int i,j;
printf("Enter the number of villages: ");
scanf("%d",&n);
printf("\nEnter the Cost Matrix\n");
for(i=0;i < n;i++)
{
printf("\nEnter Elements of Row: %d\n",i+1);
for( j=0;j < n;j++)
scanf("%d",&ary[i][j]);
completed[i]=0;
}
printf("\n\nThe cost list is:");
for( i=0;i < n;i++)
{
printf("\n");
for(j=0;j < n;j++)
printf("\t%d",ary[i][j]);
}
}
void mincost(int city)
{
int i,ncity;
completed[city]=1;
printf("%d--->",city+1);
ncity=least(city);
if(ncity==999)
{
ncity=0;
printf("%d",ncity+1);
cost+=ary[city][ncity];
return;
}
mincost(ncity);
}
int least(int c)
{
int i,nc=999; int
min=999,kmin;
for(i=0;i < n;i++)
{
if((ary[c][i]!=0)&&(completed[i]==0))
if(ary[c][i]+ary[i][c] < min)
{
min=ary[i][0]+ary[c][i];
kmin=ary[c][i];
nc=i;
}
}
if(min!=999) cost+=kmin;
return nc;
}
int main()
{
takeInput();
printf("\n\nThe Path is:\n");
mincost(0); //passing 0 because starting vertex
printf("\n\nMinimum cost is %d\n ",cost);
return 0;
}
OUTPUT:
Lab No 6:
Q)Implement Minimum Spanning Tree Algorithms – Prims Algorithms
and Kruskal Algorithm
PRIMS ALGORITHM
PROGRAM:
#include<stdio.h>
#include<conio.h>
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
void main()
{
printf("\n Enter the number of nodes:");
scanf("%d",&n);
printf("\n Enter the adjacency matrix:\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++) {
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
visited[1]=1;
printf("\n");
while(ne<n) {
for (i=1,min=999;i<=n;i++)
for (j=1;j<=n;j++)
if(cost[i][j]<min)
if(visited[i]!=0) {
min=cost[i][j];
a=u=i;
b=v=j;
}
if(visited[u]==0 || visited[v]==0) {
printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);
mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n Minimun cost=%d",mincost);
}
OUTPUT:
KRUSKALS ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);
void main()
{
printf("\nEnter the no. of vertices:");
scanf("%d",&n);
printf("\nEnter the cost adjacency matrix:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
}
printf("The edges of Minimum Cost Spanning Tree are\n");
while(ne < n)
{
for(i=1,min=999;i<=n;i++)
{
for(j=1;j <= n;j++)
{
if(cost[i][j] < min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find(u);
v=find(v);
if(uni(u,v))
{
printf("%d edge (%d,%d) =%d\n",ne++,a,b,min);
mincost +=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n\tMinimum cost = %d\n",mincost);
}
int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}
int uni(int i,int j)
{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}
OUTPUT:
General program
Age calculated program:
#include<stdio.h>
#include<conio.h>
int main()
{
int day,mon,year;
int day1,mon1,year1;
int rday,rmon,ryear;
int month[]={31,28,31,30,31,30,31,31,30,31,30,31};
printf("enter the birth date(D/M/Y):");
scanf("%d,%d,%d",&day,&mon,&year);
printf("enter the present date(D/M/Y):");
scanf("%d,%d,%d",&day1,&mon1,&year1);
if(day>day1)
{
day1=day1+month[mon-1];
mon1=mon1-1;
}
if(mon>mon1)
{
mon1=mon1+12;
year1=year1-1;
}
rday=day1-day;
rmon=mon1-mon;
ryear=year1-year;
printf("calculated age=%d/%d/%d\n",rday,rmon,ryear);
}
OUTPUT:
Lab No 7:
Q)Single Source Shortest Path Algorithms and other Graph Algorithms
like connected components.
CODE:
DIJKSTRA’S ALGORITHM
#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10
void dijikstra(int G[MAX][MAX], int n, int startnode);
void main()
{
int G[MAX][MAX], i, j, n, u;
printf("\nEnter the no. of vertices:: ");
scanf("%d", &n);
printf("\nEnter the adjacency matrix::\n");
for(i=0;i < n;i++) for(j=0;j < n;j++)
scanf("%d", &G[i][j]);
printf("\nEnter the starting node:: ");
scanf("%d", &u);
dijikstra(G,n,u);
getch();
}
void dijikstra(int G[MAX][MAX], int n, int startnode)
{
int cost[MAX][MAX], distance[MAX], pred[MAX];
int visited[MAX], count, mindistance, nextnode, i,j;
for(i=0;i < n;i++) for(j=0;j < n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];
for(i=0;i< n;i++)
{
distance[i]=cost[startnode][i];
pred[i]=startnode; visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count < n-1){
mindistance=INFINITY;
for(i=0;i<n;i++)
if(distance[i]<mindistance && !visited[i])
{
mindistance=distance[i];
nextnode=i;
}
visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}
for(i=0;i<n;i++)
if(i!=startnode)
{
printf(“\nDistance of %d=%d”,i,distance[i]);
printf(“\nPath=%d”,i);
j=i;
do{
j=pred[j];
printf(“<-%d”,j);
}while(j!=startnode);
}
}
OUTPUT:
Lab No 8:
Q)Implement the Sum of Subsets Problem.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define TRUE 1
#define FALSE 0 int inc[50],w[50],sum,n;
int promising(int i,int wt,int total)
{
return(((wt+total)>=sum)&&((wt==sum)||(wt+w[i+1]<=sum)));
}
void main()
{
int i,j,n,temp,total=0;
printf("\n Enter how many numbers:");
scanf("%d",&n);
printf("\n Enter %d numbers to the set:\n",n);
for (i=0;i<n;i++)
{
scanf("%d",&w[i]);
total+=w[i];
}
printf("\n Input the sum value to create sub set:\n");
scanf("%d",&sum);
for (i=0;i<=n;i++)
for (j=0;j<n-1;j++)
if(w[j]>w[j+1])
{
temp=w[j];
w[j]=w[j+1];
w[j+1]=temp;
}
printf("\n The given %d numbers in ascending order:\n",n);
for (i=0;i<n;i++)
printf("%d \t",w[i]);
if((total<sum))
printf("\n Subset construction is not possible");
else {
for (i=0;i<n;i++)
inc[i]=0;
printf("\n The solution using backtracking is:\n");
sumset(-1,0,total);
}
}
void sumset(int i,int wt,int total)
{
int j;
if(promising(i,wt,total))
{
if(wt==sum)
{
printf("\n{\t");
for (j=0;j<=i;j++)
if(inc[j])
printf("%d\t",w[j]);
printf("}\n");
}
else
{
inc[i+1]=TRUE;
sumset(i+1,wt+w[i+1],total-w[i+1]);
inc[i+1]=FALSE;
sumset(i+1,wt,total-w[i+1]);
}
}
}
OUTPUT:
Lab No 9:
Q)Implementation of any scheme to solve the SUDOKU puzzle.
PROGRAM:
#include <stdio.h>
int isAvailable(int puzzle[][9], int row, int col, int num)
{
int rowStart = (row/3) * 3;
int colStart = (col/3) * 3;
int i, j;
for(i=0; i<9; ++i)
{
if (puzzle[row][i] == num)
return 0;
if (puzzle[i][col] == num)
return 0;
if (puzzle[rowStart + (i%3)][colStart + (i/3)] == num)
return 0;
}
return 1;
}
int fillSudoku(int puzzle[][9], int row, int col)
{
int i;
if(row<9 && col<9)
{
if(puzzle[row][col] != 0)
{
if((col+1)<9)
return fillSudoku(puzzle, row, col+1);
else if((row+1)<9)
return fillSudoku(puzzle, row+1, 0);
else
return 1;
}
else
{
for(i=0; i<9; ++i)
{
if(isAvailable(puzzle, row, col, i+1))
{
puzzle[row][col] = i+1;
if((col+1)<9)
{
if(fillSudoku(puzzle, row, col +1))
return 1;
else
puzzle[row][col] = 0;
}
else if((row+1)<9)
{
if(fillSudoku(puzzle, row+1, 0))
return 1;
else
puzzle[row][col] = 0;
}
else
return 1;
}
}
}
return 0;
}
else
return 1;
}
int main()
{
int i, j;
int puzzle[9][9]={{0, 0, 0, 0, 0, 0, 0, 9, 0},
{1, 9, 0, 4, 7, 0, 6, 0, 8},
{0, 5, 2, 8, 1, 9, 4, 0, 7},
{2, 0, 0, 0, 4, 8, 0, 0, 0},
{0, 0, 9, 0, 0, 0, 5, 0, 0},
{0, 0, 0, 7, 5, 0, 0, 0, 9},
{9, 0, 7, 3, 6, 4, 1, 8, 0},
{5, 0, 6, 0, 8, 1, 0, 7, 4},
{0, 8, 0, 0, 0, 0, 0, 0, 0}};
if(fillSudoku(puzzle, 0, 0))
{
printf("\n+-----+-----+-----+\n");
for(i=1; i<10; ++i)
{
for(j=1; j<10; ++j)
printf("|%d", puzzle[i-1][j-1]);
printf("|\n");
if (i%3 == 0)
printf("+-----+-----+-----+\n");
}
}
else
printf("\n\nNO SOLUTION\n\n");
return 0;
}
Output:
+-----+-----+-----+
|7|4|8|6|3|5|2|9|1|
|1|9|3|4|7|2|6|5|8|
|6|5|2|8|1|9|4|3|7|
+-----+-----+-----+
|2|6|5|9|4|8|7|1|3|
|8|7|9|1|2|3|5|4|6|
|3|1|4|7|5|6|8|2|9|
+-----+-----+-----+
|9|2|7|3|6|4|1|8|5|
|5|3|6|2|8|1|9|7|4|
|4|8|1|5|9|7|3|6|2|
+-----+-----+-----+
Lab No 10:
Q)Implement N Queens Problem using the Back Trackin.
#include<stdio.h>
#include<math.h>
int board[20],count;
int main()
{
int n,i,j;
void queen(int row,int n);
printf("****N Queens Problem Using Backtracking****");
printf("\n\nEnter number of Queens:");
scanf("%d",&n);
queen(1,n);
return 0;
}
void print(int n)
{
int i,j;
printf("\n\nSolution %d:\n\n",++count);
for(i=1;i<=n;++i)
printf("\t%d",i);
for(i=1;i<=n;++i)
{
printf("\n\n%d",i);
for(j=1;j<=n;++j) //for nxn board
{
if(board[i]==j)
printf("\tQ"); //queen at i,j position else
printf("\t-"); //empty slot
}
}
}
int place(int row,int column)
{
int i;
for(i=1;i<=row-1;++i)
{
if(board[i]==column)
return 0;
else
if(abs(board[i]-column)==abs(i-row))
return 0;
}
return 1;
}
void queen(int row,int n)
{
int column;
for(column=1;column<=n;++column)
{
if(place(row,column))
{
board[row]=column;
if(row==n)
print(n);
else
queen(row+1,n);
}
}
}
OUTPUT: