0% found this document useful (0 votes)
0 views

Srishti Practical File

The document is a practical file for the Design and Analysis of Algorithms course, submitted by Srishti Mudgal. It includes various programming tasks, such as implementing sorting algorithms (like Insertion, Selection, and Quick Sort) and search algorithms (like Linear and Binary Search), along with their time complexity analysis. The document contains code snippets for each algorithm and a detailed index of the programs included.

Uploaded by

Ashutosh Kewat
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
0% found this document useful (0 votes)
0 views

Srishti Practical File

The document is a practical file for the Design and Analysis of Algorithms course, submitted by Srishti Mudgal. It includes various programming tasks, such as implementing sorting algorithms (like Insertion, Selection, and Quick Sort) and search algorithms (like Linear and Binary Search), along with their time complexity analysis. The document contains code snippets for each algorithm and a detailed index of the programs included.

Uploaded by

Ashutosh Kewat
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/ 48

[Department of Information Technology]

[Design and Analysis of Algorithm]


(240301)
[Practical file]
Submitted to: - Prof. Vishwas Shrivastava sir

Submitted by: - Srishti Mudgal


(0901AI201061)
INDEX

S.No. Program name Page No. Remarks


1 1. WAP to implement the following using array 3 - 19
as data structure and analyse its time complexity.
a. Insertion sort b. Selection sort c.
Bubble sort d. Quick sort e. Merge sort f.
Bucket sort g. Shell sort h. Radix sort i.
Heap sort
2 WAP to implement Linear and Binary Search 20 - 21
and analyze its time complexity.
3 WAP to implement Matrix Chain Multiplication 21 - 24
and analyze its time complexity.
4 WAP to implement Longest Common 25 - 26
Subsequence Problem and analyze its time
complexity.
5 WAP to implement Optimal Binary Search Tree 27 - 28
Problem and analyze its time complexity.
6 WAP to implement Huffman Coding and 29- 35
analyze its time complexity.
7 WAP to implement Dijkstra’s Algorithm and analyze 35 - 38
its time complexity
8 WAP to implement Bellman Ford Algorithm and 39 - 42
analyze its time complexity.
9 WAP to implement DFS and BFS and analyze 43 - 46
their time complexities.
10 WAP to Implement 0/1 knapsack using dynamic 47
programming.
1) WAP to implement the following using array as data structure and
analyse its time complexity.
A, Insertion sort
Code-
#include <bits/stdc++.h>
using namespace std;
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
int arr[] = {13, 15, 25, 2, 7};
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printArray(arr, n);
return 0;
}
Output

B, Selection sort
Code-
#include <bits/stdc++.h>
using namespace std;
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
for (i = 0; i < n - 1; i++)
{
min_idx = i;
for (j = i + 1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
swap(&arr[min_idx], &arr[i]);
}
}
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
cout << "Sorted array: \n";
printArray(arr, n);
return 0;
}
Output –

C, Bubble sort
Code-
#include <bits/stdc++.h>
using namespace std;
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(&arr[j], &arr[j + 1]);
}
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver code
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
cout << "Sorted array: \n";
printArray(arr, n);
return 0;
}

Output-

D, Quick Sort
Code-
#include <bits/stdc++.h>
using namespace std;
int partition(int arr[], int l, int h)
{
int pivot = arr[l];
int i = l;
int j = h;
while (i < j)
{
while (arr[i] <= pivot && i < j)
i++;
while (arr[j] > pivot && i <= j)
j--;
if (i < j)
{
swap(arr[i], arr[j]);
}
}
swap(arr[l], arr[j]);
return j;
}
void quicksort(int arr[], int l, int h)
{
if (l < h)
{
int pivot = partition(arr, l, h);
quicksort(arr, l, pivot - 1);
quicksort(arr, pivot + 1, h);
}
}
int main()
{
int arr[6] = {7, 8, 2, 5, 1, 0};
cout << "array after sorting:" << endl;
quicksort(arr, 0, 5);
for (int i = 0; i < 6; i++)
{
cout << arr[i] << " ";
}
return 0;
}

Output –
E, Bucket sort
#include <stdio.h>
#include <stdlib.h>
#define NARRAY 7 // Array size
#define NBUCKET 6 // Number of buckets
#define INTERVAL 10 // Each bucket capacity
struct Node
{
int data;
struct Node *next;
};
void BucketSort(int arr[]);
struct Node *InsertionSort(struct Node *list);
void print(int arr[]);
void printBuckets(struct Node *list);
int getBucketIndex(int value);
void BucketSort(int arr[])
{
int i, j;
struct Node **buckets;
buckets = (struct Node **)malloc(sizeof(struct
Node *) * NBUCKET);
for (i = 0; i < NBUCKET; ++i)
{
buckets[i] = NULL;
}
for (i = 0; i < NARRAY; ++i)
{
struct Node *current;
int pos = getBucketIndex(arr[i]);
current = (struct Node *)malloc(sizeof(struct
Node));
current->data = arr[i];
current->next = buckets[pos];
buckets[pos] = current;
}
for (i = 0; i < NBUCKET; i++)
{
printf("Bucket[%d]: ", i);
printBuckets(buckets[i]);
printf("\n");
}
for (i = 0; i < NBUCKET; ++i)
{
buckets[i] = InsertionSort(buckets[i]);
}
printf(" -------------\n");
printf("Bucktets after sorting\n");
for (i = 0; i < NBUCKET; i++)
{
printf("Bucket[%d]: ", i);
printBuckets(buckets[i]);
printf("\n");
}
for (j = 0, i = 0; i < NBUCKET; ++i)
{
struct Node *node;
node = buckets[i];
while (node)
{
arr[j++] = node->data;
node = node->next;
}
}
return;
}
struct Node *InsertionSort(struct Node *list)
{
struct Node *k, *nodeList;
if (list == 0 || list->next == 0)
{
return list;
}
nodeList = list;
k = list->next;
nodeList->next = 0;
while (k != 0)
{
struct Node *ptr;
if (nodeList->data > k->data)
{
struct Node *tmp;
tmp = k;
k = k->next;
tmp->next = nodeList;
nodeList = tmp;
continue;
}
for (ptr = nodeList; ptr->next != 0; ptr =
ptr->next)
{
if (ptr->next->data > k->data)
break;
}
if (ptr->next != 0)
{
struct Node *tmp;
tmp = k;
k = k->next;
tmp->next = ptr->next;
ptr->next = tmp;
continue;
}
else
{
ptr->next = k;
k = k->next;
ptr->next->next = 0;
continue;
}
}
return nodeList;
}
int getBucketIndex(int value)
{
return value / INTERVAL;
}
void print(int ar[])
{
int i;
for (i = 0; i < NARRAY; ++i)
{
printf("%d ", ar[i]);
}
printf("\n");
}

void printBuckets(struct Node *list)


{
struct Node *cur = list;
while (cur)
{
printf("%d", cur->data);
cur = cur->next;
}
}
int main(void)
{
int array[NARRAY] = {42, 32, 33, 52, 37, 47, 51};
printf(" --- \n");

printf("Initial array: ");


print(array);

BucketSort(array);

printf(" \n");
printf("Sorted array: ");

print(array);
return 0;
}
Output –
F, Radix sort
Code –
#include <iostream>
using namespace std;
int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
void countSort(int arr[], int n, int exp)
{
int output[n];
int i, count[10] = {0};
for (i = 0; i < n; i++)
count[(arr[i] / exp) % 10]++;
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--)
{
output[count[(arr[i] / exp) % 10] - 1] =
arr[i];
count[(arr[i] / exp) % 10]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
void radixsort(int arr[], int n)
{
int m = getMax(arr, n);
for (int exp = 1; m / exp > 0; exp *= 10)
countSort(arr, n, exp);
}
void print(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
int main()
{
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr) / sizeof(arr[0]);
radixsort(arr, n);
print(arr, n);
return 0;
}

Output –

G, Heap sort
Code-
#include <iostream>
using namespace std;
void heapify(int arr[], int n, int i)
{
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < n && arr[l] > arr[largest])
largest = l;
if (r < n && arr[r] > arr[largest])
largest = r;
if (largest != i)
{
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
void heapSort(int arr[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i >= 0; i--)
{
swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}
void printArray(int arr[], int n)
{
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << "\n";
}
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
heapSort(arr, n);
cout << "Sorted array is \n";
printArray(arr, n);
}

Output –

H, Merge sort
Code –
#include <stdio.h>
int main()
{
int n1, n2, n3, i, j, k;
printf("\nEnter the size of first array :
");
scanf("%d", &n1);
printf("\nEnter the size of second array :
");
scanf("%d", &n2);
n3 = n1 + n2;
printf("\nEnter the sorted array 1
elements : ");
int A[n1], B[n2], C[n3];
for (int i = 0; i < n1; i++)
{
scanf("%d", &A[i]);
C[k] = A[i];
k++;
i++;
}
printf("\nEnter the sorted array 2
elements : ");
for (int j = 0; j < n2; j++)
{
scanf("%d", &B[j]);
C[k] = B[j];
k++;
j++;
}
printf("Merged Array is : ");
for (k = 0; k < (n1 + n2); k++)
{
printf("%d ", C[k]);
}
return 0;
}
TIME COMPLEXITY:

Sorting Best Average Worst


Algorithm
Selection sort Ω(n^2) θ(n^2) O(n^2)

Bubble sort Ω(n) θ(n^2) O(n^2)

Insertion Sort Ω(n) θ(n^2) O(n^2)

Heap Sort Ω(n log(n)) θ(n log(n)) O(n log(n))

Quick sort Ω(n log(n)) θ(n log(n)) O(n^2)

Merge sort Ω(n log(n)) θ(n log(n)) O(n log(n))

Bucket Sort Ω(n+k) θ(n+k) O(n^2)

Radix Sort Ω(nk) θ(nk) O(nk)


2, WAP to implement Linear and Binary Search and analyze its time Complexity.
Code-
#include <bits/stdc++.h>
using namespace std;
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1,
x);
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}
int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]);
int result = binarySearch(arr, 0, n - 1, x);
(result == -1)
? cout << "Element is not present in
array"
: cout << "Element is present at index "
<< result;
return 0;
}
Output-

TIME COMPLEXITY:
• TIME COMPLEXITY OF LINEAR SEARCH - O(N)
• Binary search has time complexity O(log n).
3 WAP to implement Matrix Chain Multiplication and analyze its complexity

Code-
#include <iostream>
#include <limits.h>

using namespace std;

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


1..n

int MatrixChainMultiplication(int p[], int n)


{
int m[n][n];
int i, j, k, L, q;

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


m[i][i] = 0; //number of multiplications
are 0(zero) when there is only one matrix

//Here L is chain length. It varies from


length 2 to length n.
for (L = 2; L < n; L++)
{
for (i = 1; i < n - L + 1; i++)
{
j = i + L - 1;
m[i][j] = INT_MAX; //assigning to
maximum value

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


{
q = m[i][k] + m[k + 1][j] + p[i
- 1] * p[k] * p[j];
if (q < m[i][j])
{
m[i][j] = q; //if number of
multiplications found less that number will be
updated.
}
}
}
}
return m[1][n - 1]; //returning the final
answer which is M[1][n]
}

int main()
{
int n, i;
cout << "Enter number of matrices\n";
cin >> n;

n++;

int arr[n];

cout << "Enter dimensions \n";

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


{
cout << "Enter d" << i << " :: ";
cin >> arr[i];
}

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

cout<<"Minimum number of multiplications is


"<<MatrixChainMultiplication(arr, size);

return 0;
}
Output-

The time complexity of the above top-down solution is O(n3) and requires O(n2)
extra space, where n is the total number of matrices.
4, WAP to implement Longest Common Subsequence Problem and
analyze its time complexity.

Code-
Output-

TIME COMPLEXITY: TIME COMPLEXITY OF LONGEST COMMON SUBSEQUENCE


PROBLEM O(M * N)
5, WAP to implement Optimal Binary Search Tree Problem and analyze its time
complexity

Code-
Output-

TIME COMPLEXITY OF OPTIMAL BINARY SEARCH TREE PROBLEM O(LOG N).


6, WAP to implement Huffman coding and analyze its time complexity

Code-
#include <stdio.h>
#include <stdlib.h>
#define MAX_TREE_HT 100
struct MinHeapNode
{
char data;
unsigned freq;
struct MinHeapNode *left, *right;
};
struct MinHeap
{
unsigned size;
unsigned capacity;
struct MinHeapNode **array;
};
struct MinHeapNode *newNode(char data, unsigned
freq)
{
struct MinHeapNode *temp = (struct
MinHeapNode *)malloc(
sizeof(struct MinHeapNode));
temp->left = temp->right = NULL;
temp->data = data;
temp->freq = freq;
return temp;
}
struct MinHeap *createMinHeap(unsigned capacity)
{
struct MinHeap *minHeap = (struct MinHeap
*)malloc(sizeof(struct MinHeap));
minHeap->size = 0;
minHeap->capacity = capacity;
minHeap->array = (struct MinHeapNode
**)malloc(
minHeap->capacity * sizeof(struct
MinHeapNode *));
return minHeap;
}
void swapMinHeapNode(struct MinHeapNode **a,
struct MinHeapNode **b)
{
struct MinHeapNode *t = *a;
*a = *b;
*b = t;
}
void minHeapify(struct MinHeap *minHeap, int
idx)
{
int smallest = idx;
int left = 2 * idx + 1;
int right = 2 * idx + 2;
if (left < minHeap->size && minHeap-
>array[left]->freq < minHeap->array[smallest]-
>freq)
smallest = left;
if (right < minHeap->size && minHeap-
>array[right]->freq < minHeap->array[smallest]-
>freq)
smallest = right;
if (smallest != idx)
{
swapMinHeapNode(&minHeap-
>array[smallest],
&minHeap->array[idx]);
minHeapify(minHeap, smallest);
}
}
int isSizeOne(struct MinHeap *minHeap)
{
return (minHeap->size == 1);
}
struct MinHeapNode *extractMin(struct MinHeap
*minHeap)
{
struct MinHeapNode *temp = minHeap-
>array[0];
minHeap->array[0] = minHeap->array[minHeap-
>size - 1];
--minHeap->size;
minHeapify(minHeap, 0);
return temp;
}
void insertMinHeap(struct MinHeap *minHeap,
struct MinHeapNode
*minHeapNode)
{
++minHeap->size;
int i = minHeap->size - 1;
while (i && minHeapNode->freq < minHeap-
>array[(i - 1) / 2]->freq)
{
minHeap->array[i] = minHeap->array[(i -
1) / 2];
i = (i - 1) / 2;
}
minHeap->array[i] = minHeapNode;
}
void buildMinHeap(struct MinHeap *minHeap)
{
int n = minHeap->size - 1;
int i;
for (i = (n - 1) / 2; i >= 0; --i)
minHeapify(minHeap, i);
}
void printArr(int arr[], int n)
{
int i;
for (i = 0; i < n; ++i)
printf("%d", arr[i]);
printf("\n");
}
int isLeaf(struct MinHeapNode *root)
{
return !(root->left) && !(root->right);
}
struct MinHeap *createAndBuildMinHeap(char
data[],
int
freq[], int size)
{
struct MinHeap *minHeap =
createMinHeap(size);
for (int i = 0; i < size; ++i)
minHeap->array[i] = newNode(data[i],
freq[i]);
minHeap->size = size;
buildMinHeap(minHeap);
return minHeap;
}
struct MinHeapNode *buildHuffmanTree(char
data[],
int freq[],
int size)
{
struct MinHeapNode *left, *right, *top;
struct MinHeap *minHeap =
createAndBuildMinHeap(data, freq, size);
while (!isSizeOne(minHeap))
{
left = extractMin(minHeap);
right = extractMin(minHeap);
top = newNode('$', left->freq + right-
>freq);
top->left = left;
top->right = right;
insertMinHeap(minHeap, top);
}
return extractMin(minHeap);
}
void printCodes(struct MinHeapNode *root, int
arr[],
int top)
{
if (root->left)
{
arr[top] = 0;
printCodes(root->left, arr, top + 1);
}
if (root->right)
{
arr[top] = 1;
printCodes(root->right, arr, top + 1);
}
if (isLeaf(root))
{
printf("%c: ", root->data);
printArr(arr, top);
}
}
void HuffmanCodes(char data[], int freq[], int
size)
{
struct MinHeapNode *root =
buildHuffmanTree(data, freq, size);
int arr[MAX_TREE_HT], top = 0;
printCodes(root, arr, top);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f'};
int freq[] = {5, 9, 12, 13, 16, 45};
int size = sizeof(arr) / sizeof(arr[0]);
HuffmanCodes(arr, freq, size);
return 0;
}

Output-

THE TIME COMPLEXITY OF THE HUFFMAN ALGORITHM IS O(NLOGN)

7, WAP to implement Dijkstra’s Algorithm and analyze its complexity .


Code-
#include <stdio.h>
#include <conio.h>
#define INFINITY 9999
#define MAX 10
void dijkstra(int G[MAX][MAX], int n, int
startnode);
int main()
{
int G[MAX][MAX], i, j, n, u;
printf("Enter 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);
dijkstra(G, n, u);
return 0;
}
void dijkstra(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 node %d = %d\
n", i, distance[i]);
printf("\nPath=%d ", i);
j = i;
do
{
j = pred[j];
printf("<-%d", j);
} while (j != startnode);
}
}

Output-
TIME COMPLEXITY OF DIJKSTRA'S ALGORITHM IS O ( V 2 )

8, WAP to implement Bellmen Ford Algorithm and analyze its time complexity

Code-
#include <bits/stdc++.h>
struct Edge
{
int src, dest, weight;
};
struct Graph
{
int V, E;
struct Edge *edge;
};
struct Graph *createGraph(int V, int E)
{
struct Graph *graph = new Graph;
graph->V = V;
graph->E = E;
graph->edge = new Edge[E];
return graph;
}
void printArr(int dist[], int n)
{
printf("Vertex Distance from Source\n");
for (int i = 0; i < n; ++i)
printf("%d \t\t %d\n", i, dist[i]);
}
void BellmanFord(struct Graph *graph, int src)
{
int V = graph->V;
int E = graph->E;
int dist[V];
for (int i = 0; i < V; i++)
dist[i] = INT_MAX;
dist[src] = 0;
for (int i = 1; i <= V - 1; i++)
{
for (int j = 0; j < E; j++)
{
int u = graph->edge[j].src;
int v = graph->edge[j].dest;
int weight = graph->edge[j].weight;
if (dist[u] != INT_MAX && dist[u] +
weight < dist[v])
dist[v] = dist[u] + weight;
}
}
for (int i = 0; i < E; i++)
{
int u = graph->edge[i].src;
int v = graph->edge[i].dest;
int weight = graph->edge[i].weight;
if (dist[u] != INT_MAX && dist[u] +
weight < dist[v])
{
printf("Graph contains negative
weight cycle");
return;
}
}
printArr(dist, V);
return;
}
int main()
{
int V = 5; // Number of vertices in graph
int E = 8; // Number of edges in graph
struct Graph *graph = createGraph(V, E);
graph->edge[0].src = 0;
graph->edge[0].dest = 1;
graph->edge[0].weight = -1;
graph->edge[1].src = 0;
graph->edge[1].dest = 2;
graph->edge[1].weight = 4;
graph->edge[2].src = 1;
graph->edge[2].dest = 2;
graph->edge[2].weight = 3;
graph->edge[3].src = 1;
graph->edge[3].dest = 3;
graph->edge[3].weight = 2;
graph->edge[4].src = 1;
graph->edge[4].dest = 4;
graph->edge[4].weight = 2;
graph->edge[5].src = 3;
graph->edge[5].dest = 2;
graph->edge[5].weight = 5;
graph->edge[6].src = 3;
graph->edge[6].dest = 1;
graph->edge[6].weight = 1;
graph->edge[7].src = 4;
graph->edge[7].dest = 3;
graph->edge[7].weight = -3;
BellmanFord(graph, 0);
return 0;
}
Output-

TIME COMPLEXITY:
• WORST CASE TIME COMPLEXITY: Θ(VE)
• Average case time complexity: Θ(VE)
• Best case time complexity: Θ(E)

9, WAP to implement DFS and BFS and analyze its time complexity
DFS
Code-
#include <stdio.h>
int a[20][20], reach[20], n;
void dfs(int v)
{
int i;
reach[v] = 1;
for (i = 1; i <= n; i++)
if (a[v][i] && !reach[i])
{
printf("\n %d->%d", v, i);
dfs(i);
}
}
int main()
{
int i, j, count = 0;
printf("\n Enter number of vertices:");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
reach[i] = 0;
for (j = 1; j <= n; j++)
a[i][j] = 0;
}
printf("\n Enter the adjacency matrix:\n");
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
scanf("%d", &a[i][j]);
dfs(1);
printf("\n");
for (i = 1; i <= n; i++)
{
if (reach[i])
count++;
}
if (count == n)
printf("\n Graph is connected");
else
printf("\n Graph is not connected");
}
Output-

TIME COMPLEXITY OF DFS IS ALSO O(V+E) WHERE V IS VERTICES AND E IS EDGES.

 BFS
Code-
Output-
TIME COMPLEXITY OF BFS = O(V+E) WHERE V IS VERTICES AND E IS EDGES.
10, WAP to implement 0/1 knapsack using dynamic programming.

Code-

Output-

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy