50% found this document useful (2 votes)
2K views59 pages

Ada Practical

The document describes implementations and analyses of various sorting and searching algorithms: 1. Insertion sort, bubble sort, and selection sort are implemented and their time complexities of best, average, and worst cases are analyzed and printed out. 2. Heap sort and max-heap construction are implemented for sorting. Recursive and iterative implementations of factorial are presented along with counting operations. 3. Merge sort is implemented using a divide and conquer approach. Operations like dividing, combining, and comparing subsets are counted. The overall time complexity is printed as O(nLogn). 4. Binary search is outlined but its implementation and analysis are not shown in full.

Uploaded by

REEYA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
50% found this document useful (2 votes)
2K views59 pages

Ada Practical

The document describes implementations and analyses of various sorting and searching algorithms: 1. Insertion sort, bubble sort, and selection sort are implemented and their time complexities of best, average, and worst cases are analyzed and printed out. 2. Heap sort and max-heap construction are implemented for sorting. Recursive and iterative implementations of factorial are presented along with counting operations. 3. Merge sort is implemented using a divide and conquer approach. Operations like dividing, combining, and comparing subsets are counted. The overall time complexity is printed as O(nLogn). 4. Binary search is outlined but its implementation and analysis are not shown in full.

Uploaded by

REEYA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 59

ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

PRACTICAL:1
AIM: Introduction to profiling in C and Implement and analyze algorithms
given below
1.1 Insertion Sort
#include <stdio.h>
int main()
{
int n, i, j, temp;
int arr[64];

printf("Enter number of elements\n");


scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
for (i = 1 ; i <= n - 1; i++)
{
j = i;
while ( j > 0 && arr[j-1] > arr[j])
{
temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
j--;
}
}
printf("Sorted list in ascending order:\n");
for (i = 0; i <= n - 1; i++)
{
printf("%d\n", arr[i]);
}
printf("\n Complexity : \n Best case = \n");
printf("\n Complexity : \n Avg case = \n");
printf("\n Complexity : \n Worst case =\n");
return 0;
}

Er.no.190553107005 Page 1
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

OUTPUT:-

Avg case Worst case:

Best case:

Er.no.190553107005 Page 2
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

1.2 Bubble Sort

#include<stdio.h>
#include<conio.h>
int main()
{
int array[100], n, c, d,pass=0,exchanges=0,comparisons=0,stmt_counter=0,swap;
printf("worst case\n");
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c< n; c++)
{
scanf("%d", &array[c]);
}
for (c = 0 ; c < ( n - 1 ); c++)
{
pass++;

stmt_counter+=3;
for (d = 0 ; d < n - c - 1; d++)
{
comparisons++;

stmt_counter+=3;
if (array[d] > array[d+1])
{

Er.no.190553107005 Page 3
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
exchanges++;
stmt_counter+=4;
}
stmt_counter++;
}
stmt_counter++;
}
printf("Sorted list in ascending order:\n");
for(c = 0 ; c < n ; c++ )
{
printf("%d\n", array[c]);
}
printf("\n bubble sort time Complexity : \n Best case =O(n) \n");
printf(" \n Avg case =O(n²) \n");
printf(" \n Worst case =O(n²) \n");
}

Er.no.190553107005 Page 4
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

OUTPUT:-
Avg case : Best case:

Worst case:

Er.no.190553107005 Page 5
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

1.3 Selection Sort

#include <stdio.h>
void selectionSort(int arr[], int size);
void swap(int *a, int *b);
/*
* Selection sort function
*/
void selectionSort(int arr[], int size)
{
int i, j;
for (i = 0 ; i < size;i++)
{
for (j = i ; j < size; j++)
{
if (arr[i] > arr[j])
swap(&arr[i], &arr[j]);
}
}
}
/* Function to swap two variables */
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;

Er.no.190553107005 Page 6
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

}
int main()
{
int array[10], i, size;
printf("Best case\n");
printf("How many numbers you want to sort: ");
scanf("%d", &size);
printf("\nEnter %d numbers\t", size);
printf("\n");
for (i = 0; i < size; i++)
scanf("%d", &array[i]);
selectionSort(array, size);
printf("\nSorted array is ");
for (i = 0; i < size;i++)
printf(" %d ", array[i]);
printf("\n selection sort time Complexity :O(n) \n Best case =O(n) \n");
printf(" \n Avg case =O(n²) \n");
printf(" \n Worst case =O(n²) \n");
return 0;
}

Er.no.190553107005 Page 7
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

OUTPUT:-
Avg case: Best case:

Worst case:

Er.no.190553107005 Page 8
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

PRACTICAL: 2

AIM: Implement and analyze algorithms given below.


2.1 Max-Heap sort
#include <stdio.h>
void main()
{
int heap[10], no, i, j, c, root, temp;
printf("\n Enter no of elements :");
scanf("%d", &no);
printf("\n Enter the nos : ");
for (i = 0; i < no; i++)
scanf("%d", &heap[i]);
for (i = 1; i < no; i++)
{
c = i;
do {
root = (c - 1) / 2;
if (heap[root] < heap[c]) /* to create MAX heap array */ {
temp = heap[root];
heap[root] = heap[c];
heap[c] = temp;
}
c = root;
} while (c != 0);
}
printf("Heap array : ");

Er.no.190553107005 Page 9
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

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


printf("%d\t ", heap[i]);
for (j = no - 1; j >= 0; j--) {
temp = heap[0];
heap[0] = heap[j]; /* swap max element with rightmost leaf element */
heap[j] = temp;
root = 0;
do {
c = 2 * root + 1; /* left node of root element */
if ((heap[c] < heap[c + 1]) && c < j-1)
c++;
if (heap[root]<heap[c] && c<j) /* again rearrange to max heap array */ {
temp = heap[root];
heap[root] = heap[c];
heap[c] = temp;
}
root = c;
} while (c < j);
}
printf("\n The sorted array is : ");
for (i = 0; i < no; i++)
printf("\t %d", heap[i]);
printf("\n Complexity : \n Best case = Avg case = Worst case = O(n logn) \n");
}

Er.no.190553107005 Page 10
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

OUTPUT:-

Er.no.190553107005 Page 11
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

PRACTICAL: 3
AIM: Implement and analyze algorithms given below.
3.1 Iterative Factorial

#include<stdio.h>
void main()
{
int a,b;
int flag=0;
int sum=1;
flag++;
printf("enter value of number:");
scanf("%d",&b);
flag++;
for(a=1;a<b+1;a++)
{
flag++;
flag++;
sum=sum*a;
flag++;
}
flag++;
printf("Factorial=%d ",sum);
printf("\nCount=%d",flag);
}

Er.no.190553107005 Page 12
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

OUTPUT:-

Er.no.190553107005 Page 13
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

3.2 Recursive Factorial


#include <stdio.h>
int r (int a1);
int flag=0;
void main()
{
int b;
int ans;
printf("enter value of number:");
scanf("%d",&b);
flag++;
flag++;
ans=r(b);
printf("%d",ans);
printf("\n%d",flag);
}
r(int a1)
{
flag++;
if(a1>0)
{
flag++;
flag++;
flag++;
return (a1*r(a1-1));
}

Er.no.190553107005 Page 14
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

OUTPUT:-

Er.no.190553107005 Page 15
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

PRACTICAL:4
AIM: Implement and analyze algorithms given below.( Divide and Conquer
Strategy)
4.1 Merge Sort
#include<stdio.h>
#include<conio.h>
void merge(int [],int ,int ,int );
void part(int [],int ,int );
int divide=0,combine=0,cmp=0,c=0;
int main()
{
int arr[30];
int i,size;
printf("\n\t------- Merge sorting method -------\n\n");
printf("Enter total no. of elements : ");
scanf("%d",&size);
for(i=0; i<size; i++)
{
printf("Enter %d element : ",i+1);
scanf("%d",&arr[i]);
}
part(arr,0,size-1);
printf("\n\t------- Merge sorted elements -------\n\n");
for(i=0; i<size; i++)
printf("%d ",arr[i]);
printf("\nDivide: %d",divide-1);
printf("\nCombine: %d",combine);
printf("\nCompare/Conquer: %d",cmp);
printf(“\n complexity: O(n*Log n) \n”);
printf("\nTotal Count: %d",c);
return 0;
}
void part(int arr[],int min,int max)
{
c++;
divide++;
int mid;
if(min<max)
{
c++;
mid=(min+max)/2;
part(arr,min,mid);
part(arr,mid+1,max);

Er.no.190553107005 Page 16
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

merge(arr,min,mid,max);
}
}
void merge(int arr[],int min,int mid,int max)
{
c++;
combine++;
int tmp[30];
int i,j,k,m;
j=min;
m=mid+1;
for(i=min; j<=mid && m<=max ; i++)
{
c+=2;
if(arr[j]<=arr[m])
{
c++;
cmp++;
tmp[i]=arr[j];
j++;
}
else
{
c++;
cmp++;
tmp[i]=arr[m];
m++;
}
}
if(j>mid)
{
c++;
for(k=m; k<=max; k++)
{
c+=2;
tmp[i]=arr[k];
i++;
}
}
else
{
c++;
for(k=j; k<=mid; k++)
{
c+=2;
tmp[i]=arr[k];

Er.no.190553107005 Page 17
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

i++;
}
}
for(k=min; k<=max; k++)
{
c+=2;
arr[k]=tmp[k];
}
}

Er.no.190553107005 Page 18
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

OUTPUT:-

Er.no.190553107005 Page 19
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

4.2 Binary Search


#include<stdio.h>
int main()
{
int a[50],i,n,m,c=0,l,u,mid,count,s;
count=0;
s=0;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements in ascending order: ");
for(i=0; i<n; i++)
{
count+=2;
scanf("%d",&a[i]);
}
printf("Enter the number to be search: ");
scanf("%d",&m);
l=0,u=n-1;
count+=1;
while(l<=u)
{
s+=1;
count+=1;
mid=(l+u)/2;
count+=1;
if(m==a[mid])
{
count+=2;
c=1;
break;
}
else if(m<a[mid])
{
count+=2;
u=mid-1;
}
else
{
l=mid+1;
count+=1;
}
}
if(c==0)
{
count+=1;
printf("The number is not found.");
Er.no.190553107005 Page 20
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

}
else
{
printf("The number is found.");
}

printf("\n\tcount :: %d \n\n",count);
printf("\tsearch :: %d\n",s);
return 0;
}

Er.no.190553107005 Page 21
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

OUTPUT:-

Er.no.190553107005 Page 22
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

4.3 Quick Sort


#include<stdio.h>
int divide=0,cmp=0,c=0;
void swap (int a[], int left, int right)
{
cmp++;
int temp;
c++;
temp=a[left];
a[left]=a[right];
a[right]=temp;
}
void quicksort( int a[], int low, int high )
{
c++;
int pivot;
if ( high > low )
{
c++;
pivot = partition( a, low, high );
quicksort( a, low, pivot-1 );
quicksort( a, pivot+1, high );
}
}
int partition( int a[], int low, int high )
{
c++;
divide++;
int left, right;
int pivot_item;
int pivot = left = low;
pivot_item = a[low];
right = high;
while ( left < right )
{
c++;
while( a[left] <= pivot_item )
{
c++;
left++;
}
while( a[right] >pivot_item )
{
c++;
right--;
}
Er.no.190553107005 Page 23
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

if ( left < right )


{
c++;
swap(a,left,right);
}
}
a[low] = a[right];
a[right] = pivot_item;
return right;
}
voidprintarray(int a[], int);
int main()
{
int a[50], i, n;
printf("\nEnter no. of elements: ");
scanf("%d", &n);
printf("\nEnter the elements: \n");
for (i=0; i<n; i++)
scanf ("%d", &a[i]);
quicksort(a,0,n-1);
printf("\nSorted elements: \n");
printarray(a,n);
printf("\nDivide: %d",divide);
printf("\nCompare/Conquer: %d",cmp);

printf("\nTotal Count: %d",c);


}
void printarray(int a[], int n)
{
int i;
for (i=0; i<n; i++)
printf(" %d ", a[i]);
printf("\n");
}

Er.no.190553107005 Page 24
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

OUTPUT:-

Er.no.190553107005 Page 25
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

PRACTICAL:5
AIM: Implement and analyze algorithm given below. (Greedy Approach)
5.1 Making Change Problem

#include <stdio.h>
int coins[] = { 1,5,10,25,100 };
int findMaxCoin(int amount, int size){
for(int i=0; i<size; i++){
if(amount < coins[i]) return i-1;
}
return -1;
}
int findMinimumCoinsForAmount(int amount, int change[]){
int numOfCoins = sizeof(coins)/sizeof(coins[0]);
int count = 0;
while(amount){
int k = findMaxCoin(amount, numOfCoins);
if(k == -1)
printf("No viable solution");
else{
amount-= coins[k];
change[count++] = coins[k];
}
}
return count;
}
int main(void) {
int change[10]; // This needs to be dynamic
int amount = 34;
int count = findMinimumCoinsForAmount(amount, change);
printf("\n Number of coins for change of %d : %d", amount, count);
printf("\n Coins : ");
for(int i=0; i<count; i++){
printf("%d ", change[i]);
}
printf("\n Greedy Making Change Problem Time Complexity : O(n log n) + O(amount)");
return 0;
}

Er.no.190553107005 Page 26
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

OUTPUT:-

Er.no.190553107005 Page 27
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

5.2 Knapsack Problem


#include <bits/stdc++.h>

using namespace std;

// Structure for an item which stores weight and corresponding


// value of Item
struct Item
{
int value, weight;

// Constructor
Item(int value, int weight) : value(value), weight(weight)
{}
};

// Comparison function to sort Item according to val/weight ratio


bool cmp(struct Item a, struct Item b)
{
double r1 = (double)a.value / a.weight;
double r2 = (double)b.value / b.weight;
return r1 > r2;
}

// Main greedy function to solve problem


double fractionalKnapsack(int W, struct Item arr[], int n)
{
// sorting Item on basis of ratio
sort(arr, arr + n, cmp);

// Uncomment to see new order of Items with their ratio

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


{
cout << arr[i].value << " " << arr[i].weight << " : "
<< ((double)arr[i].value / arr[i].weight) << endl;
}
int curWeight = 0; // Current weight in knapsack
double finalvalue = 0.0; // Result (value in Knapsack)

Er.no.190553107005 Page 28
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

// Looping through all Items


for (int i = 0; i < n; i++)
{
// If adding Item won't overflow, add it completely
if (curWeight + arr[i].weight <= W)
{
curWeight += arr[i].weight;
finalvalue += arr[i].value;
}

// If we can't add current Item, add fractional part of it


else
{
int remain = W - curWeight;
finalvalue += arr[i].value * ((double) remain / arr[i].weight);
printf("Maximum value we can obtain : ", finalvalue);
break;
}
}

// Returning final value


return finalvalue;
}

int main()
{
int W = 50; // Weight of knapsack
Item arr[] = {{60, 10}, {100, 20}, {120, 30}};

int n = sizeof(arr) / sizeof(arr[0]);

cout << "Ratio = "


<< fractionalKnapsack(W, arr, n);
cout << "\n Fractional Knapsack Problem Time Complexity : O(n log2 n)" ;
return 0;
}

Er.no.190553107005 Page 29
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

OUTPUT:-

Er.no.190553107005 Page 30
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

PRACTICAL:6
AIM: Solve and Design given problem (Dynamic Programming)
6.1 Making Change
Dynamic Making Change Problem:-
#include<iostream>
#include<algorithm>
#include<climits>
using namespace std;

int changeMaking(int coin[], int n, int sum)


{
int i,j;
int x,y;

//matrix to tabulate results


int dp[n+1][sum+1];

//dp[i][j]=minimum no. of coins required to change j using only i coins

//initialization
//if there is no coin, then infinite no. of coins will be required to change j
for(j=0;j<=sum;j++)
dp[0][j]=INT_MAX;

//if value to be changed is 0, then no coin is required


for(i=1;i<=n;i++)
dp[i][0]=0;

//i represents the number of coins being used


for(i=1;i<=n;i++)
{
//j represents the amount whose change is required
for(j=1;j<=sum;j++)
{
//if the value of current coin is less than or equal to the amount whose change is required,
then first include the coin and then exclude the coin
//compare both the results and select the one which takes minimum no. of coins
if(j>=coin[i-1])

Er.no.190553107005 Page 31
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

{
//without including the current coin
x=dp[i-1][j];

//the current coin is included(hence 1+)


y=1+dp[i][j-coin[i-1]];

//the lesser value out of both is taken


dp[i][j]=min(x,y);
}

//If value of current coin is greater than the amount, this coin can not be included
else
dp[i][j]=dp[i-1][j];
}

}
return dp[n][sum];
}
int main()
{
int i;
int n,sum;
cout<<"Enter the amount whose change is required"<<endl;
cin>>sum;
cout<<"Enter the number of coins available"<<endl;
cin>>n;
int coin[n];
cout<<"Enter the values of coins"<<endl;
for(i=0;i<n;i++)
cin>>coin[i];
cout<<"The least number of coins whose sum is equal to required sum is"<<endl;
cout<<changeMaking(coin,n,sum);
cout<<"\n Time Complexity of Making Change Problem in Dynamic Programming is :
O(mn)"<<endl;
cout<<endl;
return 0;
}

Er.no.190553107005 Page 32
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

OUTPUT:-

Er.no.190553107005 Page 33
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

6.2 Knapsack Problem


#include<stdio.h>
#include<conio.h>
#define MAX 20
void knapsackDP(int,int);
int max(int,int);
int count=0;
void backtracking();
int weight[MAX],value[MAX],W,no,*x;
int v[MAX][MAX];
main()
{
int i,j;
printf("\nEnter number of Object you want:");
scanf("%d",&no);
printf("\nEnter weight and values in ascending order of values");;
for(i=1;i<=no;i++){
printf("\nEnter Weight and Value for Object %d:",i);
scanf("%d %d",&weight[i],&value[i]);
}
printf("\nEnter knapsack Capacity:");
scanf("%d",&W);
count++; //function calling
knapsackDP(no,W);
count++; //function calling
backtracking();
printf("\nCount:%d",count);
printf("\n Time complexity of 0 1 Knapsack problem is : O(nW) where, n is the number of
items and W is the capacity of knapsack.");
}
void knapsackDP(int no,int W){
int i,j;
count++; //initialize i
for(i=0;i<=W;i++){
count++; //condition true
v[0][i]=0;
count+=2; //assign value and increment i
}
count++; //condition false
count++; //initialize i

Er.no.190553107005 Page 34
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

for(i=0;i<=no;i++){
count++; //condition true
v[i][0]=0;
count+=2; //assign value and increment i
}
count++; //condition false
count++; //initialize i
for(i=1;i<=no;i++){
count+=2; //initialize j and condition true
for(j=1;j<=W;j++){
count++; //condition true
if((j-weight[i])<0){
count++; //condition true
v[i][j]=v[i-1][j];
count++; //assign value
}
else{
count++; //condition false
count++; //function calling
v[i][j]=max(v[i-1][j],v[i-1][j-weight[i]]+value[i]);
count++; //assign value
}
count++; //increment j
}
count++; //increment i
}
printf("\n \t ");
for(i=0;i<= W;i++)
printf("%2d ",i);
printf("\n-----------------------------------------------------------------------------");
for(i=0;i<=no;i++){
printf("\n w%d=%2d v%d=%2d |",i,weight[i],i,value[i]);
for(j=0;j<= W;j++)
printf("%2d ",v[i][j]);
}
printf("\n-----------------------------------------------------------------------------");
printf("\n Maximum value carry by knapsack is:%2d",v[no][W]);
printf("\n-----------------------------------------------------------------------------");
}
int max(int a,int b){
count++; //return value
Er.no.190553107005 Page 35
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

return (a >b)?a:b;
}
void backtracking(){
int j1,i;
j1=W;
count++; //assign value to j1
printf("\nIncluded Object \t weight \t value");
printf("\n-----------------------------------------------------------------------------");
count++; //initialize i
for(i=no;i>=0;i--){
count++; //condition true
if(v[i][j1]!=v[i-1][j1] && (v[i][j1]==v[i-1][j1-weight[i]]+value[i])){
count+=2; //condition true
printf("\n%2d \t\t\t %2d \t\t %2d",i,weight[i],value[i]);
j1=j1-weight[i];
count++; //decrement j1
}
count+=2; //condition false and decrement i
}
count++; //condition false
}

OUTPUT:-

Er.no.190553107005 Page 36
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

PRACTICAL:7
Er.no.190553107005 Page 37
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

AIM: Implement given problem.


7.1 Matrix Chain Multiplication
#include <stdio.h>
#include<limits.h>
#define INFY 999999999
long int m[20][20];
int s[20][20];
int p[20],i,j,n;

void print_optimal(int i,int j)


{
if (i == j)
printf(" A%d ",i);
else
{
printf("( ");
print_optimal(i, s[i][j]);
print_optimal(s[i][j] + 1, j);
printf(" )");
}
}

void matmultiply(void)
{
long int q;
int k;
for(i=n;i>0;i--)
{
for(j=i;j<=n;j++)
{
if(i==j)
m[i][j]=0;
else
{
for(k=i;k<j;k++)
{
q=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j];
if(q<m[i][j])
{

Er.no.190553107005 Page 38
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

m[i][j]=q;
s[i][j]=k;
}
}
}
}
}
}

int MatrixChainOrder(int p[], int i, int j)


{
if(i == j)
return 0;
int k;
int min = INT_MAX;
int count;

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


{
count = MatrixChainOrder(p, i, k) +
MatrixChainOrder(p, k+1, j) +
p[i-1]*p[k]*p[j];

if (count < min)


min = count;
}

// Return minimum count


return min;
}

void main()
{
int k;
printf("Enter the no. of elements: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
for(j=i+1;j<=n;j++)
{
m[i][i]=0;
m[i][j]=INFY;

Er.no.190553107005 Page 39
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

s[i][j]=0;
}
printf("\nEnter the dimensions: \n");
for(k=0;k<=n;k++)
{
printf("P%d: ",k);
scanf("%d",&p[k]);
}
matmultiply();
printf("\nCost Matrix M:\n");
for(i=1;i<=n;i++)
for(j=i;j<=n;j++)
printf("m[%d][%d]: %ld\n",i,j,m[i][j]);

i=1,j=n;
printf("\nMultiplication Sequence : ");
print_optimal(i,j);
printf("\nMinimum number of multiplications is : %d ",
MatrixChainOrder(p, 1, n));
printf("\n Complexity of MCM is : O (n3)");
}

OUTPUT:-

Er.no.190553107005 Page 40
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

7.2 LCS Problem


#include<stdio.h>

Er.no.190553107005 Page 41
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

#include<string.h>

int i,j,m,n,c[20][20];
char x[20],y[20],b[20][20];

void print(int i,int j)


{
if(i==0 || j==0)
return;
if(b[i][j]=='c')
{
print(i-1,j-1);
printf("%c",x[i-1]);
}
else if(b[i][j]=='u')
print(i-1,j);
else
print(i,j-1);
}

void lcs()
{
m=strlen(x);
n=strlen(y);
for(i=0;i<=m;i++)
c[i][0]=0;
for(i=0;i<=n;i++)
c[0][i]=0;

//c, u and l denotes cross, upward and downward directions respectively


for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
{
if(x[i-1]==y[j-1])
{
c[i][j]=c[i-1][j-1]+1;
b[i][j]='c';
}
else if(c[i-1][j]>=c[i][j-1])
{
c[i][j]=c[i-1][j];
b[i][j]='u';
}
else
{
c[i][j]=c[i][j-1];

Er.no.190553107005 Page 42
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

b[i][j]='l';
}
}
}

int main()
{
printf("Enter 1st sequence:");
scanf("%s",x);
printf("Enter 2nd sequence:");
scanf("%s",y);
printf("\nThe Longest Common Subsequence is ");
lcs();
print(m,n);
printf("\n Complexity of LCS in Brute Force is: O(2^n) ");
printf("\n Complexity of LCS in Dynamic Programming is: O(mn)");
return 0;
}

OUTPUT:-

Er.no.190553107005 Page 43
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

PRACTICAL:8

Er.no.190553107005 Page 44
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

AIM: Implement given below. (Graph)


8.1 DFS Graph
#include<stdio.h>

void DFS(int);
int G[10][10],visited[10],n; //n is no of vertices and graph is sorted in array G[10][10]

void main()
{
int i,j;
printf("Enter number of vertices:");

scanf("%d",&n);

//read the adjecency matrix


printf("\nEnter adjecency matrix of the graph:");

for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);

//visited is initialized to zero


for(i=0;i<n;i++)
visited[i]=0;

DFS(0);
}

void DFS(int i)
{
int j;
printf("\n%d",i);
visited[i]=1;

for(j=0;j<n;j++)
if(!visited[j]&&G[i][j]==1)
DFS(j);
}

OUTPUT:-

Er.no.190553107005 Page 45
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

8.2 BFS Graph

Er.no.190553107005 Page 46
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

#include<stdio.h>
#include<stdlib.h>

#define MAX 100

#define initial 1
#define waiting 2
#define visited 3

int n;
int adj[MAX][MAX];
int state[MAX];
void create_graph();
void BF_Traversal();
void BFS(int v);

int queue[MAX], front = -1,rear = -1;


void insert_queue(int vertex);
int delete_queue();
int isEmpty_queue();

int main()
{
create_graph();
BF_Traversal();
return 0;
}

void BF_Traversal()
{
int v;

for(v=0; v<n; v++)


state[v] = initial;

printf("Enter Start Vertex for BFS: \n");


scanf("%d", &v);
BFS(v);
}

void BFS(int v)
{
int i;

insert_queue(v);
state[v] = waiting;

Er.no.190553107005 Page 47
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

while(!isEmpty_queue())
{
v = delete_queue( );
printf("%d ",v);
state[v] = visited;

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


{
if(adj[v][i] == 1 && state[i] == initial)
{
insert_queue(i);
state[i] = waiting;
}
}
}
printf("\n");
}

void insert_queue(int vertex)


{
if(rear == MAX-1)
printf("Queue Overflow\n");
else
{
if(front == -1)
front = 0;
rear = rear+1;
queue[rear] = vertex ;
}
}

int isEmpty_queue()
{
if(front == -1 || front > rear)
return 1;
else
return 0;
}

int delete_queue()
{
int delete_item;
if(front == -1 || front > rear)
{
printf("Queue Underflow\n");

Er.no.190553107005 Page 48
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

exit(1);
}

delete_item = queue[front];
front = front+1;
return delete_item;
}

void create_graph()
{
int count,max_edge,origin,destin;

printf("Enter number of vertices : ");


scanf("%d",&n);
max_edge = n*(n-1);

for(count=1; count<=max_edge; count++)


{
printf("Enter edge %d( -1 -1 to quit ) : ",count);
scanf("%d %d",&origin,&destin);

if((origin == -1) && (destin == -1))


break;

if(origin>=n || destin>=n || origin<0 || destin<0)


{
printf("Invalid edge!\n");
count--;
}
else
{
adj[origin][destin] = 1;
}
}
}

OUTPUT:-
Er.no.190553107005 Page 49
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

PRACTICAL:9
Er.no.190553107005 Page 50
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

AIM: Solves the problem.


9.1 n Queen Problem
#include<stdio.h>
#include<math.h>
int stmt_counter=0;
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);
/*counter for function call*/
stmt_counter++;
queen(1,n);
printf("\nTotal solution=%d",count);
printf("\nTotal count=%d",stmt_counter);
printf("\n Time complexity of N-queen Problem is : O(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){
if(board[i]==j)
printf("\tQ");
else
printf("\t-");
}
}
}
int place(int row,int column){
int i;
/*counter for initialization of i in for loop*/
stmt_counter++;
for(i=1;i<=row-1;++i){
/*counter for condition checking and increment operation*/
stmt_counter+=2;
/*counter for if condition*/

Er.no.190553107005 Page 51
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

stmt_counter++;
if(board[i]==column)
return 0;
else if(abs(board[i]-column)==abs(i-row)){
/*counter for else if condition*/
stmt_counter++;
return 0;
}
}
return 1;
}
void queen(int row,int n){
int column;
/*counter for initialization of column*/
stmt_counter++;
for(column=1;column<=n;++column){
/*counter for condition and increment operation in for loop*/
stmt_counter+=2;
/*counter for if condition*/
stmt_counter++;
if(place(row,column)){
/*counter for assignment*/
stmt_counter++;
board[row]=column;
/*counnter for if condition checking*/
stmt_counter++;
if(row==n){
/*counter for function call*/
stmt_counter++;
print(n);
}
else{
/*counter for function call*/
stmt_counter++;
queen(row+1,n);
}
}
/*counter for incrementation of column*/
stmt_counter++;
}
/*counter for false condition*/
stmt_counter++;
}

OUTPUT:-
Er.no.190553107005 Page 52
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

PRACTICAL:10

Er.no.190553107005 Page 53
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

AIM: Implement given below.


10.1 Prim’s Algorithm
#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()

//clrscr();

printf("\nEnter the number of nodes:");

scanf("%d",&n);

printf("\nEnter 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++)

Er.no.190553107005 Page 54
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

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

getch();

OUTPUT:-

Er.no.190553107005 Page 55
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

10.2 Kruskal’s Algorithm

Er.no.190553107005 Page 56
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

#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()
{
//clrscr();
printf("\n\tImplementation of Kruskal's algorithm\n");
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;

Er.no.190553107005 Page 57
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

}
printf("\n\tMinimum cost = %d\n",mincost);
getch();
}
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:-
Er.no.190553107005 Page 58
ENGINEERING COLLEGE TUWA Analysis And Design of Algorithms (3150703)

Er.no.190553107005 Page 59

You might also like