Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

Dr.

Jivraj Mehta Institute of Technology


Mogar, Anand

CERTIFICATE
This is certified that Mr./Ms.

Of 5th semester, Enrollment number of Department of

Computer Engineering has satisfactorily completed his work in lab for the term ending in

in the subject of Analysis and Design of algorithm (3150710).

Date:

Signature of Teacher Head of Department


ADA (3150703) Enrollment No.: 210820107013

LIST OF PRACTICALS

Sr. Title of Practical Page Date of Date of Signature


no. Experiment Submission

1 Implementation and Time analysis 2


of sorting algorithms. Bubble sort,
Selection sort, Insertion sort,
Merge sort and Quicksort
2 Implementation and Time analysis 17
of linear and binary search
algorithm.
3 Implementation of max-heap sort 21
algorithm

4 Implementation and Time analysis 25


of factorial program using iterative
and recursive method
5 Implementation of a knapsack 27
problem using dynamic
programming.
6 Implementation of chain matrix 31
multiplication using dynamic
programming.
7 Implementation of making a 33
change problem using dynamic
programming

8 Implementation of a knapsack 35
problem using greedy algorithm

9 Implementation of Graph and 38


Searching (DFS and BFS).

10 Implement prim’s algorithm 43


11 Implement kruskal’s algorithm. 45

12 Implement LCS problem. 50

DJMIT - CSE 1
ADA (3150703) Enrollment No.: 210820107013

Practical 1

Aim: Implementation and Time analysis of sorting algorithms. Bubble sort, Selection
sort, Insertion sort, Merge sort and Quicksort.

1. Bubble Sort

C Program:

// Bubble sort in C

#include <stdio.h>

// perform the bubble sort

void bubbleSort(int array[], int size) {

// loop to access each array element

for (int step = 0; step < size - 1; ++step) {

// loop to compare array elements


for (int i = 0; i < size - step - 1; ++i) {

// compare two adjacent elements

// change > to < to sort in descending order

if (array[i] > array[i + 1]) {

// swapping occurs if elements

// are not in the intended order

int temp = array[i];


array[i] = array[i + 1];
array[i + 1] = temp;

DJMIT - CSE 2
ADA (3150703) Enrollment No.: 210820107013

}
}
}
}

// print array

void printArray(int array[], int size) {

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

printf("%d ", array[i]);


}
printf("\n");
}

int main() {
// Array implementation

int x=0;
int data[4];
for (x=0; x<4;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &data[x]);
}

// find the array's length

int size = sizeof(data) / sizeof(data[0]);

bubbleSort(data, size);

printf("Sorted Array in Ascending Order:\n");

printArray(data, size);
}

DJMIT - CSE 3
ADA (3150703) Enrollment No.: 210820107013

Output:

3459

Bubble Sort Complexity:

Time Complexity

Best O(n)

Worst O(n2)

Average O(n2)

Space Complexity O(1)

Stability Yes

DJMIT - CSE 4
ADA (3150703) Enrollment No.: 210820107013

2. Selection sort

C Program:

// Selection sort in C

#include <stdio.h>

// function to swap the the position of two elements

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

void selectionSort(int array[], int size) {

for (int step = 0; step < size - 1; step++) {

int min_idx = step;

for (int i = step + 1; i < size; i++) {

// To sort in descending order, change > to < in this line.

// Select the minimum element in each loop.

if (array[i] < array[min_idx])

min_idx = i;
}

// put min at the correct position

swap(&array[min_idx], &array[step]);
}
}

DJMIT - CSE 5
ADA (3150703) Enrollment No.: 210820107013

// function to print an array

void printArray(int array[], int size) {


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

printf("%d ", array[i]);

}
printf("\n");
}

// driver code

int main() {
int x=0;
int data[4];

for (x=0; x<4;x++)


{
printf("Enter number %d \n", (x+1));
scanf("%d", &data[x]);
}

int size = sizeof(data) / sizeof(data[0]);

selectionSort(data, size);

printf("Sorted array in Ascending Order:\n");

printArray(data, size);
}

DJMIT - CSE 6
ADA (3150703) Enrollment No.: 210820107013

Output:

Enter number 1
5
Enter number 2
9
Enter number 3
2
Enter number 4
6
Sorted array in Ascending Order:
2569

...Program finished with exit code 0


Press ENTER to exit console.

Selection Sort Complexity:

Time Complexity

Best O(n2)

Worst O(n2)

Average O(n2)

Space Complexity O(1)

Stability No

DJMIT - CSE 7
ADA (3150703) Enrollment No.: 210820107013

3. Insertion sort

C Program:

// Insertion sort in C

#include <stdio.h>

// Function to print an array


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

void insertionSort(int array[], int size) {


for (int step = 1; step < size; step++) {
int key = array[step];
int j = step - 1;

/* Compare key with each element on the left of it until an element smaller than it is
found. For descending order, change key<array[j] to key>array[j].*/
while (key < array[j] && j >= 0) {
array[j + 1] = array[j];
--j;
}
array[j + 1] = key;
}
}

// Driver code
int main() {
int x=0;
int data[4];
for (x=0; x<4;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &data[x]);

DJMIT - CSE 8
ADA (3150703) Enrollment No.: 210820107013

}
int size = sizeof(data) / sizeof(data[0]);

insertionSort(data, size);

printf("Sorted array in ascending order:\n");

printArray(data, size);
}

Output:

Enter number 1
6
Enter number 2
9
Enter number 3
8
Enter number 4
2
Sorted array in ascending order:
2 6 89

...Program finished with exit code 0


Press ENTER to exit console.

Insertion Sort Complexity:

Time Complexity
Best O(n)
Worst O(n2)
Average O(n2)
Space Complexity O(1)
Stability Yes

DJMIT - CSE 9
ADA (3150703) Enrollment No.: 210820107013

4. Merge sort

C Program:

// Merge sort in C

#include <stdio.h>

// Merge two subarrays L and M into arr

void merge(int arr[], int p, int q, int r) {

// Create L ← A[p..q] and M ← A[q+1..r]

int n1 = q - p + 1;
int n2 = r - q;

int L[n1], M[n2];

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


L[i] = arr[p + i];
for (int j = 0; j < n2; j++)
M[j] = arr[q + 1 + j];

// Maintain current index of sub-arrays and main array

int i, j, k;
i = 0;
j = 0;
k = p;

// Until we reach either end of either L or M, pick larger among

// elements L and M and place them in the correct position at A[p..r]

while (i < n1 && j < n2) {


if (L[i] <= M[j]) {
arr[k] = L[i];
i++;

DJMIT - CSE 10
ADA (3150703) Enrollment No.: 210820107013

}
else
{
arr[k] = M[j];
j++;
}
k++;
}

// When we run out of elements in either L or M,

// pick up the remaining elements and put in A[p..r]

while (i < n1) {


arr[k] = L[i];
i++;
k++;
}

while (j < n2) {


arr[k] = M[j];
j++;
k++;
}
}

// Divide the array into two subarrays, sort them and merge them

void mergeSort(int arr[], int l, int r) {


if (l < r) {

// m is the point where the array is divided into two subarrays

int m = l + (r - l) / 2;

mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);

// Merge the sorted subarrays

DJMIT - CSE 11
ADA (3150703) Enrollment No.: 210820107013

merge(arr, l, m, r);
}
}

// Print the array

void printArray(int arr[], int size) {


for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver program

int main() {
int x=0;
int arr[4];

for (x=0; x<4;x++)


{
printf("Enter number %d \n", (x+1));
scanf("%d", &arr[x]);
}

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

mergeSort(arr, 0, size - 1);

printf("Sorted array: \n");

printArray(arr, size);
}

DJMIT - CSE 12
ADA (3150703) Enrollment No.: 210820107013

Output:

Enter number 1
5
Enter number 2
9
Enter number 3
3
Enter number 4
1
Sorted array:
1359

...Program finished with exit code 0


Press ENTER to exit console.

Merge Sort Complexity:

Time Complexity

Best O(n*log n)

Worst O(n*log n)

Average O(n*log n)

Space Complexity O(n)

Stability Yes

DJMIT - CSE 13
ADA (3150703) Enrollment No.: 210820107013

5. Quicksort

C Program:

// Quick sort in C

#include <stdio.h>

void swap(int *a, int *b) {


int t = *a;
*a = *b;
*b = t;
}

int partition(int array[], int low, int high) {

// select the rightmost element as pivot


int pivot = array[high];
// pointer for greater element
int i = (low - 1);

// traverse each element of the array


for (int j = low; j < high; j++) {
if (array[j] <= pivot) {

// if element smaller than pivot is found


// swap it with the greater element pointed by i
i++;

// swap element at i with element at j


swap(&array[i], &array[j]);
}
}

// swap the pivot element with the greater element at i


swap(&array[i + 1], &array[high]);

// return the partition point


return (i + 1);
}

DJMIT - CSE 14
ADA (3150703) Enrollment No.: 210820107013

void quickSort(int array[], int low, int high) {


if (low < high) {

int pi = partition(array, low, high);

// recursive call on the left of pivot


quickSort(array, low, pi - 1);

// recursive call on the right of pivot


quickSort(array, pi + 1, high);
}
}

// function to print array elements


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

// main function
int main() {
int x=0;
int data[4];
for (x=0; x<4;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &data[x]);
}

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


printf("Unsorted Array\n");
printArray(data, n);
quickSort(data, 0, n - 1);

printf("Sorted array in ascending order: \n");


printArray(data, n);
}

DJMIT - CSE 15
ADA (3150703) Enrollment No.: 210820107013

Output:

Enter number 1
5
Enter number 2
4
Enter number 3
2
Enter number 4
9
Unsorted Array
5 4 29
Sorted array in ascending order:
2 4 59

...Program finished with exit code 0


Press ENTER to exit console.

Quicksort Complexity:

Time Complexity
Best O(n*log n)
Worst O(n2)
Average O(n*log n)
Space Complexity O(log n)
Stability No

DJMIT - CSE 16
ADA (3150703) Enrollment No.: 210820107013

Practical: 2

Aim: Implementation and Time analysis of linear and binary search algorithm.

1. Linear Search
C Program:

#include <stdio.h>
int main()
{
int array[100], search, c, n;

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


scanf("%d", &n);

printf("Enter %d integer(s)\n", n);

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


scanf("%d", &array[c]);

printf("Enter a number to search\n");


scanf("%d", &search);

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


{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d or index %d.\n", search, c+1,c);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);

return 0;
}

DJMIT - CSE 17
ADA (3150703) Enrollment No.: 210820107013

Output:

Enter number of elements in array


3
Enter 3 integer(s)
1
5
9
Enter a number to search
5
5 is present at location 2 or at index 1.
...Program finished with exit code 0
Press ENTER to exit console.

Time Analysis:

Case Time Complexity

Best Case O(1)

Average Case O(n)

Worst Case O(n)

DJMIT - CSE 18
ADA (3150703) Enrollment No.: 210820107013

2. Binary search
C Program:

// Binary Search in C

#include <stdio.h>

int binarySearch(int array[], int find, int low, int high) {


// Repeat until the pointers low and high meet each other
while (low <= high) {
int mid = low + (high - low) / 2;

if (array[mid] == find)
return mid;

if (array[mid] < find)


low = mid + 1;
else
high = mid - 1;
}
return -1;
}

int main(void) {
int x=0;
int size;
printf("Enter size of Array: \n");
scanf("%d", &size);
int array[size];
for (x=0; x<size;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &array[x]);
}
int n = sizeof(array) / sizeof(array[0]);

DJMIT - CSE 19
ADA (3150703) Enrollment No.: 210820107013

int find;
printf("Enter number to find: \n");
scanf("%d", &find);
int result = binarySearch(array, find, 0, n - 1);
if (result == -1)
printf("Not found");
else
printf("Element is found at index %d", result);
return 0;
}

Output:

Enter size of Array:


3
Enter number 1
1
Enter number 2
5
Enter number 3
9
Enter number to find:
5
Element is found at index 1

...Program finished with exit code 0


Press ENTER to exit console.

Time Analysis:

Case Time Complexity

Best Case O(1)

Average Case O(logn)

Worst Case O(logn)

DJMIT - CSE 20
ADA (3150703) Enrollment No.: 210820107013

Practical: 3

Aim: Implementation of max-heap sort algorithm.

C Program:

// Heap Sort in C

#include <stdio.h>

// Function to swap the position of two elements

void swap(int* a, int* b)


{

int temp = *a;

*a = *b;

*b = temp;
}

// To heapify a subtree rooted with node i


// which is an index in arr[].
// n is size of heap

void heapify(int arr[], int N, int i)


{
// Find largest among root, left child and right child

// Initialize largest as root


int largest = i;

// left = 2*i + 1
int left = 2 * i + 1;

// right = 2*i + 2
int right = 2 * i + 2;

DJMIT - CSE 21
ADA (3150703) Enrollment No.: 210820107013

// If left child is larger than root


if (left < N && arr[left] > arr[largest])

largest = left;

// If right child is larger than largest


// so far

if (right < N && arr[right] > arr[largest])

largest = right;

// Swap and continue heapifying if root is not largest


// If largest is not root

if (largest != i) {

swap(&arr[i], &arr[largest]);

// Recursively heapify the affected


// sub-tree

heapify(arr, N, largest);
}
}

// Main function to do heap sort

void heapSort(int arr[], int N)


{

// Build max heap


for (int i = N / 2 - 1; i >= 0; i--)

heapify(arr, N, i);

// Heap sort
for (int i = N - 1; i >= 0; i--) {

swap(&arr[0], &arr[i]);

DJMIT - CSE 22
ADA (3150703) Enrollment No.: 210820107013

// Heapify root element to get highest element at


// root again

heapify(arr, i, 0);
}
}

// A utility function to print array of size n


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

// Driver's code
int main()
{
int x=0;
int size;
printf("Enter size of Array: \n");
scanf("%d", &size);
int arr[size];
for (x=0; x<size;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &arr[x]);
}

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

// Function call

heapSort(arr, N);
printf("Sorted array is\n");
printArray(arr, N);

DJMIT - CSE 23
ADA (3150703) Enrollment No.: 210820107013

Output:

Enter size of Array:


3
Enter number 1
5
Enter number 2
9
Enter number 3
2
Sorted array is
2 59

...Program finished with exit code 0


Press ENTER to exit console.

Heap Sort Complexity

Time Complexity
Best O(nlog n)
Worst O(nlog n)
Average O(nlog n)
Space Complexity O(1)
Stability No

DJMIT - CSE 24
ADA (3150703) Enrollment No.: 210820107013

Practical: 4

Aim: Implementation and Time analysis of factorial program using iterative and
recursive method

1. Recursive method

/* Program to find the factorial of a number by recursion and iteration method*/

#include<stdio.h>
long int fact(int n);
long int Ifact(int n);

int main( )
{
int num;
printf("Enter a number : ");
scanf("%d", &num);

printf("\nUsing Recursion :: \n");


if(num<0)
printf("No factorial for negative number\n");
else
printf("Factorial of %d is %ld\n", num, fact(num) );

printf("\nUsing Iterative :: \n");

if(num<0)
printf("No factorial for negative number\n");
else
printf("Factorial of %d is %ld\n", num, Ifact(num) );

return 0;

DJMIT - CSE 25
ADA (3150703) Enrollment No.: 210820107013

}/*End of main()*/

/*Recursive*/
long int fact(int n)
{
if(n == 0)
return(1);
return(n * fact(n-1));
}/*End of fact()*/

/*Iterative*/
long int Ifact(int n)
{
long fact=1;
while(n>0)
{
fact = fact*n;
n--;
}
return fact;
}/*End of ifact()*/

Output:

Enter a number : 5

Using Recursion ::
Factorial of 5 is 120

Using Iterative ::
Factorial of 5 is 120

...Program finished with exit code 0


Press ENTER to exit console.

DJMIT - CSE 26
ADA (3150703) Enrollment No.: 210820107013

Practical: 5

Aim: Implementation of a knapsack problem using dynamic programming.

C Program:

#include <stdio.h>
#include <stdlib.h>
int W, n;
void main()
{
int w, i, l = 0, p, j;
printf("Enter number of objects \n");
scanf("%d", &n);
printf("Enter maximum weight, knapsack can carry \n");
scanf("%d", &W);
int k[n + 1][W + 1], a[W], v[W], ks[W];
printf("Enter weights of objects \n");
a[0] = 0;
for (i = 1; i < n + 1; i++)
{
printf("w[%d] = ", i);
scanf("%d", &a[i]);
}
printf("Enter profits/values of objects \n");
v[0] = 0;
for (i = 1; i < n + 1; i++)
{
printf("p[%d] = ", i);
scanf("%d", &v[i]);
}
k[0][0] = 0;
for (w = 1; w <= W; w++)
k[0][w] = 0;
for (i = 1; i <= n + 1; i++)
k[i][0] = 0;
for (i = 1; i <= n; i++)

DJMIT - CSE 27
ADA (3150703) Enrollment No.: 210820107013

{
for (w = 1; w <= W; w++)
{
if (a[i] <= w)
{
if (v[i] + k[i - 1][w - a[i]] > k[i - 1][w])
{
k[i][w] = v[i] + k[i - 1][w - a[i]];
}
else
{
k[i][w] = k[i - 1][w];
}
}
else
{
k[i][w] = k[i - 1][w];
}
}
}
printf("\n\nP W i \t0 ");
for (i = 1; i <= W; i++)
{
printf("%d ", i);
}
printf("\n \n");
for (i = 0; i < n + 1; i++)
{
printf("%d %d %d |\t", v[i], a[i], i);
for (j = 0; j <= W; j++)
{
printf("%d ", k[i][j]);
}
printf("\n");
}
i = n;
p = W;
int u = 0, x = 0;
while (i >= 0 && p >= 0)
{

DJMIT - CSE 28
ADA (3150703) Enrollment No.: 210820107013

if (k[i][W] != k[i - 1][W])


{
ks[++l] = i;
p = p - a[i];
u = u + i;
x += v[i];
i = i - 1;
}
else
i = i - 1;
}

ks[++l] = '\0';
l = 1;
printf("\nThe individual weights are ");
while (ks[l] != '\0')
{
printf("%d ", ks[l]);
l++;
}
printf("\n\nTotal weight to be carried in knapsack is %d \n\n", u);
printf("Total profit in knapsack is %d \n\n", x);
}

Output:

Enter number of objects


5
Enter maximum weight, knapsack can carry
10
Enter weights of objects
w[1] = 2
w[2] = 6
w[3] = 5
w[4] = 9
w[5] = 3
Enter profits/values of objects
p[1] = 5
p[2] = 2

DJMIT - CSE 29
ADA (3150703) Enrollment No.: 210820107013

p[3] = 3
p[4] = 4
p[5] = 1

PWi 0 1 2 3 4 5 6 7 8 9 10

0 00| 0 0 0 0 0 0 0 0 0 0 0
5 21| 0 0 5 5 5 5 5 5 5 5 5
2 62| 0 0 5 5 5 5 5 5 7 7 7
3 53| 0 0 5 5 5 5 5 8 8 8 8
4 94| 0 0 5 5 5 5 5 8 8 8 8
1 35| 0 0 5 5 5 6 6 8 8 8 9

The individual weights are 5 3 2

Total weight to be carried in knapsack is 10

Total profit in knapsack is 6

...Program finished with exit code 0


Press ENTER to exit console.

DJMIT - CSE 30
ADA (3150703) Enrollment No.: 210820107013

Practical: 6

Aim: Implementation of chain matrix multiplication using dynamic programming.

C Program:

#include <limits.h>
#include <stdio.h>

// Matrix Ai has dimension p[i-1] x p[i] for i = 1..n


int MatrixChainOrder(int p[], int i, int j)
{
if (i == j)
return 0;
int k;
int min = INT_MAX;
int count;

// place parenthesis at different places between first


// and last matrix, recursively calculate count of
// multiplications for each parenthesis placement and
// return the minimum 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;
}

// Driver program to test above function


int main()

DJMIT - CSE 31
ADA (3150703) Enrollment No.: 210820107013

{
int arr[] = { 1, 2, 3, 4, 3 };
int n = sizeof(arr) / sizeof(arr[0]);

printf("Minimum number of multiplications is %d ",


MatrixChainOrder(arr, 1, n - 1));

getchar();
return 0;
}

Output:

Minimum number of multiplications is 30

...Program finished with exit code 0


Press ENTER to exit console.

DJMIT - CSE 32
ADA (3150703) Enrollment No.: 210820107013

Practical: 7

Aim: Implementation of making a change problem using dynamic programming.

C Program:

// C program for coin change problem.


#include <stdio.h>

int count(int coins[], int n, int sum)


{
int i, j, x, y;

// We need sum+1 rows as the table is constructed


// in bottom up manner using the base case 0
// value case (sum = 0)
int table[sum + 1][n];

// Fill the entries for 0 value case (n = 0)


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

// Fill rest of the table entries in bottom


// up manner
for (i = 1; i < sum + 1; i++) {
for (j = 0; j < n; j++) {
// Count of solutions including S[j]
x = (i - coins[j] >= 0) ? table[i - coins[j]][j]
: 0;

// Count of solutions excluding S[j]


y = (j >= 1) ? table[i][j - 1] : 0;

// total count
table[i][j] = x + y;
}
}

DJMIT - CSE 33
ADA (3150703) Enrollment No.: 210820107013

return table[sum][n - 1];


}

// Driver program to test above function


int main()
{
int coins[] = { 1, 2, 3 };
int n = sizeof(coins) / sizeof(coins[0]);
int sum = 4;
printf(" %d ", count(coins, n, sum));
return 0;
}

Output:

4
...Program finished with exit code 0
Press ENTER to exit console.

DJMIT - CSE 34
ADA (3150703) Enrollment No.: 210820107013

Practical: 8

Aim: Implementation of a knapsack problem using greedy algorithm.

C Program:

#include <stdio.h>
#include <stdlib.h>
int main()
{
int m, n, i, j;
printf("Enter maximum weight of knapsack ");
scanf("%d", &m);
printf("\nEnter number of objects ");
scanf("%d", &n);
int wt = 0, k = 0;
float cal[n], p[n], w[n], x[n], prof = 0;
for (i = 0; i < n; i++)
x[i] = 0;
printf("\nEnter weights\n");
for (i = 0; i < n; i++)
{
printf("w[%d] = ", i);
scanf("%f", &w[i]);
}
printf("\nEnter profits\n");
for (i = 0; i < n; i++)
{
printf("p[%d] = ", i);
scanf("%f", &p[i]);
}
for (i = 0; i < n; i++)
cal[i] = p[i] / w[i];
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{

DJMIT - CSE 35
ADA (3150703) Enrollment No.: 210820107013

if (cal[i] < cal[j])


{
int t1, t2, t3;
t1 = cal[i];
cal[i] = cal[j];
cal[j] = t1;
t2 = w[i];
w[i] = w[j];
w[j] = t2;
t3 = p[i];
p[i] = p[j];
p[j] = t3;
}
}
}
printf("\n\n p[i]\t\t w[i]\t\t cal[i]\n");
for (i = 0; i < n; i++)
printf("%f\t %f\t %f\t\n", p[i], w[i], cal[i]);
for (i = 0; i < n; i++)
{
if ((wt + w[i]) <= m)
{
k++;
x[i] = 1;
wt += w[i];
prof += p[i];
}
else
{
k++;
x[i] = (m - wt) / w[i];
w[i] = m - wt;
wt = m;
prof += (x[i] * p[i]);
p[i] = (x[i] * p[i]);
break;
}
}
printf("\nThe selected weights are \n\ni\t w[i]\t\t p[i]\n");
for (i = 0; i < k; i++)

DJMIT - CSE 36
ADA (3150703) Enrollment No.: 210820107013

printf("%d\t%f\t%f\n", i + 1, w[i], p[i]);


printf("\n\nThe total profit is %f\n\n", prof);
return 0;
}

Output:

Enter number of objects 3

Enter weights
w[0] = 10
w[1] = 5
w[2] = 15

p[0] = 5
p[1] = 2
p[2] = 10

p[i] w[i]

5.000000 0.400000

i w[i] p[i]
1 15.000000 10.000000
2 5.000000 2.000000
3 10.000000 5.000000

The total profit is 17.000000

DJMIT - CSE 37
ADA (3150703) Enrollment No.: 210820107013

Practical: 9

Aim: Implementation of Graph and Searching (DFS and BFS).

C Program:

#include<stdio.h>

int q[20],top=-1,front=-1,rear=-1,a[20][20],vis[20],stack[20];
int delete();
void add(int item);
void bfs(int s,int n);
void dfs(int s,int n);
void push(int item);
int pop();

void main()
{
int n,i,s,ch,j;
char c,dummy;
printf("ENTER THE NUMBER VERTICES ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("ENTER 1 IF %d HAS A NODE WITH %d ELSE 0 ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("THE ADJACENCY MATRIX IS\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf(" %d",a[i][j]);
}
printf("\n");

DJMIT - CSE 38
ADA (3150703) Enrollment No.: 210820107013

do
{
for(i=1;i<=n;i++)
vis[i]=0;
printf("\nMENU");
printf("\n1.B.F.S");
printf("\n2.D.F.S");
printf("\nENTER YOUR CHOICE");
scanf("%d",&ch);
printf("ENTER THE SOURCE VERTEX :");
scanf("%d",&s);

switch(ch)
{
case 1:bfs(s,n);
break;
case 2:
dfs(s,n);
break;
}
printf("DO U WANT TO CONTINUE(Y/N) ? ");
scanf("%c",&dummy);
scanf("%c",&c);
}while((c=='y')||(c=='Y'));
}

//BFS(breadth-first search) code//

void bfs(int s,int n)


{
int p,i;
add(s);
vis[s]=1;
p=delete();
if(p!=0)
printf(" %d",p);
while(p!=0)
{

DJMIT - CSE 39
ADA (3150703) Enrollment No.: 210820107013

for(i=1;i<=n;i++)
if((a[p][i]!=0)&&(vis[i]==0))
{
add(i);
vis[i]=1;
}
p=delete();
if(p!=0)
printf(" %d ",p);
}
for(i=1;i<=n;i++)
if(vis[i]==0)
bfs(i,n);
}

void add(int item)


{
if(rear==19)
printf("QUEUE FULL");
else
{
if(rear==-1)
{
q[++rear]=item;
front++;
}
else
q[++rear]=item;
}
}
int delete()
{
int k;
if((front>rear)||(front==-1))
return(0);
else
{
k=q[front++];
return(k);

DJMIT - CSE 40
ADA (3150703) Enrollment No.: 210820107013

}
}

//DFS(depth-first search) code//

void dfs(int s,int n)


{
int i,k;
push(s);
vis[s]=1;
k=pop();
if(k!=0)
printf(" %d ",k);
while(k!=0)
{
for(i=1;i<=n;i++)
if((a[k][i]!=0)&&(vis[i]==0))
{
push(i);
vis[i]=1;
}
k=pop();
if(k!=0)
printf(" %d ",k);
}
for(i=1;i<=n;i++)
if(vis[i]==0)
dfs(i,n);
}
void push(int item)
{
if(top==19)
printf("Stack overflow ");
else
stack[++top]=item;
}
int pop()
{
int k;
if(top==-1)

DJMIT - CSE 41
ADA (3150703) Enrollment No.: 210820107013

return(0);
else
{
k=stack[top--];
return(k);
}
}

Output:
ENTER THE NUMBER VERTICES 3
ENTER 1 IF 1 HAS A NODE WITH 1 ELSE 0 1
ENTER 1 IF 1 HAS A NODE WITH 2 ELSE 0 1
ENTER 1 IF 1 HAS A NODE WITH 3 ELSE 0 0
ENTER 1 IF 2 HAS A NODE WITH 1 ELSE 0 1
ENTER 1 IF 2 HAS A NODE WITH 2 ELSE 0 0
ENTER 1 IF 2 HAS A NODE WITH 3 ELSE 0 1
ENTER 1 IF 3 HAS A NODE WITH 1 ELSE 0 0
ENTER 1 IF 3 HAS A NODE WITH 2 ELSE 0 1
ENTER 1 IF 3 HAS A NODE WITH 3 ELSE 0 1
THE ADJACENCY MATRIX IS
110
101
011

MENU
1.B.F.S
2.D.F.S
ENTER YOUR CHOICE1
ENTER THE SOURCE VERTEX :2
2 1 3 DO U WANT TO CONTINUE(Y/N) ? y
MENU
1.B.F.S
2.D.F.S
ENTER YOUR CHOICE2
ENTER THE SOURCE VERTEX :2
2 3 1 DO U WANT TO CONTINUE(Y/N) ?

...Program finished with exit code 0


Press ENTER to exit console.

DJMIT - CSE 42
ADA (3150703) Enrollment No.: 210820107013

Practical: 10

Aim: Implement prim’s algorithm.

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

int main() {
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++)
for(j=1;j<=n;j++)

if(cost[i][j]< min)
if(visited[i]!=0)
{
min=cost[i][j];
a=u=i;

DJMIT - CSE 43
ADA (3150703) Enrollment No.: 210820107013

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:

Enter the number of nodes: 3


Enter the adjacency matrix:
1 2 3
4 5 6
7 8 9

Edge 1: (1 2) cost:2
Edge 1: (1 3) cost:3
Minimum cost: 5

DJMIT - CSE 44
ADA (3150703) Enrollment No.: 210820107013

Practical: 11

Aim: Implement kruskal’s algorithm.

C Program:

// Kruskal's algorithm in C

#include <stdio.h>
#define MAX 30

typedef struct edge {


int u, v, w;
} edge;

typedef struct edge_list {


edge data[MAX];
int n;
} edge_list;

edge_list elist;

int Graph[MAX][MAX], n;
edge_list spanlist;

void kruskalAlgo();
int find(int belongs[], int vertexno);
void applyUnion(int belongs[], int c1, int c2);
void sort();
void print();

// Applying Krushkal Algo


void kruskalAlgo() {
int belongs[MAX], i, j, cno1, cno2;
elist.n = 0;

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


for (j = 0; j < i; j++) {

DJMIT - CSE 45
ADA (3150703) Enrollment No.: 210820107013

if (Graph[i][j] != 0) {
elist.data[elist.n].u = i;
elist.data[elist.n].v = j;
elist.data[elist.n].w = Graph[i][j];
elist.n++;
}
}
sort();

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


belongs[i] = i;

spanlist.n = 0;

for (i = 0; i < elist.n; i++) {


cno1 = find(belongs, elist.data[i].u);
cno2 = find(belongs, elist.data[i].v);

if (cno1 != cno2) {
spanlist.data[spanlist.n] = elist.data[i];
spanlist.n = spanlist.n + 1;
applyUnion(belongs, cno1, cno2);
}
}
}

int find(int belongs[], int vertexno) {


return (belongs[vertexno]);
}

void applyUnion(int belongs[], int c1, int c2) {


int i;

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


if (belongs[i] == c2)
belongs[i] = c1;
}

// Sorting algo
void sort() {

DJMIT - CSE 46
ADA (3150703) Enrollment No.: 210820107013

int i, j;
edge temp;

for (i = 1; i < elist.n; i++)


for (j = 0; j < elist.n - 1; j++)
if (elist.data[j].w > elist.data[j + 1].w) {
temp = elist.data[j];
elist.data[j] = elist.data[j + 1];
elist.data[j + 1] = temp;
}
}

// Printing the result


void print() {
int i, cost = 0;

for (i = 0; i < spanlist.n; i++) {


printf("\n%d - %d : %d", spanlist.data[i].u, spanlist.data[i].v, spanlist.data[i].w);
cost = cost + spanlist.data[i].w;
}

printf("\nSpanning tree cost: %d", cost);


}

int main() {
int i, j, total_cost;

n = 6;

Graph[0][0] = 0;
Graph[0][1] = 4;
Graph[0][2] = 4;
Graph[0][3] = 0;
Graph[0][4] = 0;
Graph[0][5] = 0;
Graph[0][6] = 0;

Graph[1][0] = 4;
Graph[1][1] = 0;
Graph[1][2] = 2;

DJMIT - CSE 47
ADA (3150703) Enrollment No.: 210820107013

Graph[1][3] = 0;
Graph[1][4] = 0;
Graph[1][5] = 0;
Graph[1][6] = 0;

Graph[2][0] = 4;
Graph[2][1] = 2;
Graph[2][2] = 0;
Graph[2][3] = 3;
Graph[2][4] = 4;
Graph[2][5] = 0;
Graph[2][6] = 0;

Graph[3][0] = 0;
Graph[3][1] = 0;
Graph[3][2] = 3;
Graph[3][3] = 0;
Graph[3][4] = 3;
Graph[3][5] = 0;
Graph[3][6] = 0;

Graph[4][0] = 0;
Graph[4][1] = 0;
Graph[4][2] = 4;
Graph[4][3] = 3;
Graph[4][4] = 0;
Graph[4][5] = 0;
Graph[4][6] = 0;

Graph[5][0] = 0;
Graph[5][1] = 0;
Graph[5][2] = 2;
Graph[5][3] = 0;
Graph[5][4] = 3;
Graph[5][5] = 0;
Graph[5][6] = 0;

kruskalAlgo();
print();
}

DJMIT - CSE 48
ADA (3150703) Enrollment No.: 210820107013

Output:

2-1:2
5-2:2
3-2:3
4-3:3
1-0:4
Spanning tree cost: 14

...Program finished with exit code 0


Press ENTER to exit console.

DJMIT - CSE 49
ADA (3150703) Enrollment No.: 210820107013

Practical: 12

Aim: Implement LCS problem.

C Program:

#include <stdio.h>
void lcs(int arr[][10], char ar[], int, int);
int l, k;
void main()
{
char s1[10], s2[10];
int i, j;
printf("\nEnter the strings\nX = ");
s1[0] = 0;
char ch = getchar();
while (ch != '\n')
{
s1[++l] = ch;
ch = getchar();
}
printf("Y = ");
s2[0] = 0;
char c1 = getchar();
while (c1 != '\n')
{
s2[++k] = c1;
c1 = getchar();
}

int c[l + 1][k + 1], b[l + 1][k + 1];


for (i = 0; i < l + 1; i++)
{
for (j = 0; j < k + 1; j++)
{
b[i][j] = 0;
c[i][j] = 0;
}
}

DJMIT - CSE 50
ADA (3150703) Enrollment No.: 210820107013

// 1=diagonal 2=up 3=left


for (i = 1; i < l + 1; i++)
{
for (j = 1; j < k + 1; j++)
{
if (s1[i] == s2[j])
{
c[i][j] = c[i - 1][j - 1] + 1;
b[i][j] = 1; // diagonal
}
else if (c[i - 1][j] >= c[i][j - 1])
{
c[i][j] = c[i - 1][j];
b[i][j] = 2; // up
}
else
{
c[i][j] = c[i][j - 1];
b[i][j] = 3; // left
}
}
}

printf("\n\n\t");
for (i = 1; i < k + 1; i++)
{
printf("\t %c", s2[i]);
}
printf("\n");
for (i = 0; i < l + 1; i++)
{
printf("%c\t", s1[i]);
for (j = 0; j < k + 1; j++)
{
printf("%d(%d)\t", c[i][j], b[i][j]);
}
printf("\n");
}
printf("\n\n");
printf("Longest common substring of X and Y is ");

DJMIT - CSE 51
ADA (3150703) Enrollment No.: 210820107013

lcs(b, s1, l, k);


printf("\n\n");
}
void lcs(int arr[l + 1][k + 1], char ar[l + 1], int a, int p)
{
if (a == 0 || p == 0)
return;
if (arr[a][p] == 1)
{
lcs(arr, ar, a - 1, p - 1);
printf("%c ", ar[a]);
}
else if (arr[a][p] == 2)
{
lcs(arr, ar, a - 1, p);
}
else if (arr[a][p] == 3)
{
lcs(arr, ar, a, p - 1);
}
}

Output:

Enter the strings


X = ABDF
Y = DFBA

D F B A
0(0) 0(0) 0(0) 0(0) 0(0)
0(0) 0(2) 0(2) 0(2) 1(1)
B 0(0) 0(2) 0(2) 1(1) 1(2)
D 0(0) 1(1) 1(3) 1(2) 1(2)
F 0(0) 1(2) 2(1) 2(3) 2(3)

Longest common substring of X and Y is D F

...Program finished with exit code 0


Press ENTER to exit console.

DJMIT - CSE 52

You might also like