C++ Code

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

DESIGN AND ANALYSIS OF ALGORITHMS LAB

1. Using a stack of characters, convert an infix string to postfix string.

#include<stdio.h>
#include<ctype.h>

char stack[100];
int top = -1;

void push(char x)
{
stack[++top] = x;
}

char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}

int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}

int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);

1
printf("\n");
e = exp;

while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c ",pop());
push(*e);
}
e++;
}

while(top != -1)
{
printf("%c ",pop());
}return 0;
}

Output:

Enter the expression : (a+b)*(c+d)+e

ab+ cd+ *e+

2. Implement insertion, deletion, searching of a Binary Search Tree.

Insertion of a BST

#include<stdio.h>
#include<stdlib.h>
void insert(int);
2
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *root;
void main ()
{
int choice,item;
do
{
printf("\nEnter the item which you want to insert?\n");
scanf("%d",&item);
insert(item);
printf("\nPress 0 to insert more ?\n");
scanf("%d",&choice);
}while(choice == 0);
}
void insert(int item)
{
struct node *ptr, *parentptr , *nodeptr;
ptr = (struct node *) malloc(sizeof (struct node));
if(ptr == NULL)
{
printf("can't insert");
}
else
{
ptr -> data = item;
ptr -> left = NULL;
ptr -> right = NULL;
if(root == NULL)
{
root = ptr;
root -> left = NULL;
root -> right = NULL;
}
else
{

3
parentptr = NULL;
nodeptr = root;
while(nodeptr != NULL)
{
parentptr = nodeptr;
if(item < nodeptr->data)
{
nodeptr = nodeptr -> left;
}
else
{
nodeptr = nodeptr -> right;
}
}
if(item < parentptr -> data)
{
parentptr -> left = ptr;
}
else
{
parentptr -> right = ptr;
}
}
printf("Node Inserted");
}
}
Output

Enter the item which you want to insert?

14

Node Inserted

Press 0 to insert more ?

Enter the item which you want to insert?

13

4
Node Inserted

Press 0 to insert more ?

Deletion of BST

#include<stdio.h>

#include<stdlib.h>

struct node {

int key;

struct node *left, *right;

};

// A utility function to create a new BST node

struct node *newNode(int item) {

struct node *temp = (struct node *) malloc(sizeof(struct node));

temp->key = item;

temp->left = temp->right = NULL;

return temp;

// A utility function to do inorder traversal of BST

void inorder(struct node *root) {

if (root != NULL) {

inorder(root->left);

printf("%d ", root->key);

inorder(root->right);}}

5
/* A utility function to insert a new node with given key in BST */

struct node* insert(struct node* node, int key) {

/* If the tree is empty, return a new node */

if (node == NULL)

return newNode(key);

/* Otherwise, recur down the tree */

if (key < node->key)

node->left = insert(node->left, key);

else

node->right = insert(node->right, key);

/* return the (unchanged) node pointer */

return node;

/* Given a non-empty binary search tree, return the node with minimum

key value found in that tree. Note that the entire tree does not

need to be searched. */

struct node * minValueNode(struct node* node) {

struct node* current = node;

/* loop down to find the leftmost leaf */

while (current->left != NULL)

current = current->left;

return current;

6
/* Given a binary search tree and a key, this function deletes the key

and returns the new root */

struct node* deleteNode(struct node* root, int key) {

// base case

if (root == NULL)

return root;

// If the key to be deleted is smaller than the root's key,

// then it lies in left subtree

if (key < root->key)

root->left = deleteNode(root->left, key);

// If the key to be deleted is greater than the root's key,

// then it lies in right subtree

else if (key > root->key)

root->right = deleteNode(root->right, key);

// if key is same as root's key, then This is the node

// to be deleted

else {

// node with only one child or no child

if (root->left == NULL) {

struct node *temp = root->right;

free(root);

return temp;

} else if (root->right == NULL) {

7
struct node *temp = root->left;

free(root);

return temp;

// node with two children: Get the inorder successor (smallest

// in the right subtree)

struct node* temp = minValueNode(root->right);

// Copy the inorder successor's content to this node

root->key = temp->key;

// Delete the inorder successor

root->right = deleteNode(root->right, temp->key);

return root;

// Driver Program to test above functions

int main() {

/* Let us create following BST

50

/ \

30 70

/ \ / \

20 40 60 80 */

struct node *root = NULL;

8
root = insert(root, 50);

root = insert(root, 30);

root = insert(root, 20);

root = insert(root, 40);

root = insert(root, 70);

root = insert(root, 60);

root = insert(root, 80);

printf("Inorder traversal of the given tree \n");

inorder(root);

printf("\nDelete 20\n");

root = deleteNode(root, 20);

printf("Inorder traversal of the modified tree \n");

inorder(root);

printf("\nDelete 30\n");

root = deleteNode(root, 30);

printf("Inorder traversal of the modified tree \n");

inorder(root);

printf("\nDelete 50\n");

root = deleteNode(root, 50);

printf("Inorder traversal of the modified tree \n");

inorder(root);

return 0;

9
Output

Inorder traversal of the given tree

20 30 40 50 60 70 80

Delete 20

Inorder traversal of the modified tree

30 40 50 60 70 80

Searching of BST

#include <stdio.h>

#include <stdlib.h>

struct TreeNode {

int data;

struct TreeNode *leftChildNode;

struct TreeNode *rightChildNode;

};

typedef struct TreeNode node;

node *rootNode = NULL;

/* Function to insert a node in a Binary search tree */

void insertNode(int i, node **n) {

if (*n == NULL) {

(*n) = (node*)malloc(sizeof(node));

(*n)->leftChildNode = NULL;

(*n)->rightChildNode = NULL;

(*n)->data = i;

10
}

else if ((*n)->data == i)

printf("\nThis value already exists in the tree!");

else if (i > (*n)->data)

insertNode(i, &((*n)->rightChildNode));

else

insertNode(i, &((*n)->leftChildNode));

/* End of insertNode() */

/* Function to search an element in a Binary search tree */

void searchNode(int i, node **n) {

if (*n == NULL)

printf("\nValue does not exist in tree!");

else if((*n)->data == i)

printf("\nValue found!");

else if(i > (*n)->data)

searchNode(i, &((*n)->rightChildNode));

else

searchNode(i, &((*n)->leftChildNode));

/* End of serachNode() */

11
/* The main() program begins */

int main()

int ch, num, num1;

do {

printf("\nSelect a choice from the menu below.");

printf("\n1. Insert a node.");

printf("\n2. Search for a node.");

printf("\nChoice: ");

scanf("%d", &ch);

switch(ch) {

case 1:

printf("\nEnter an element: ");

scanf("%d", &num);

insertNode(num, &rootNode);

break;

case 2:

printf("\nEnter the element to be searched for: ");

scanf("%d", &num);

searchNode(num, &rootNode);

break;

default:

exit(0);

12
}

printf("\nIf you want to return to the menu, press 1.");

printf("\nChoice: ");

scanf("%d", &num);

} while(num == 1);

return 0;

Output

Select a choice from the menu below.

1. Insert a node.

2. Search for a node.

Choice: 1

Enter an element: 45

If you want to return to the menu. Press 1.

Choice: 1

Select a choice from the menu below.

1. Insert a node.

2. Search for a node.

Choice: 1

Enter an element: 34

If you want to return to the menu. Press 1.

Choice: 1

Select a choice from the menu below.

13
1. Insert a node.

2. Search for a node.

Choice: 2

Enter the element to be searched for: 34

Value found!

If you want to return to the menu. Press 1.

Choice: 2

3.(a) Implement binary search and linear search in a program.

Binary Search

#include <stdio.h>

int main()

int i, low, high, mid, n, key, array[100];

printf("Enter number of elements:");

scanf("%d",&n);

printf("Enter %d integers", n);

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

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

printf("Enter value to find:");

scanf("%d", &key);

low = 0;

high = n - 1;

mid = (low+high)/2;

14
while (low <= high) {

if(array[mid] < key)

low = mid + 1;

else if (array[mid] == key) {

printf("%d found at location %d", key, mid+1);

break;

else

high = mid - 1;

mid = (low + high)/2;

if(low > high)

printf("Not found! %d isn't present in the list", key);

return 0;

Output

Enter number of elements:5

Enter 5 integers

56 34 23 78 12

Enter value to find:23

23 found at location 3

15
Linear Search

#include<stdio.h>

int main()

int a[20],i,x,n;

printf("Enter no of elements you want to insert:");

scanf("%d",&n);

printf("Enter array elements");

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

scanf("%d",&a[i]);

printf("Enter element to search:");

scanf("%d",&x);

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

if(a[i]==x)

break;

if(i<n)

printf("Element found at index no %d",i);

else

printf("Element not found");

return 0;

Output

Enter no of lements you want to insert:5

16
Enter array elements 45 34 28 65 49

Enter elements to search:49

Element found at index no 4

(b) Implement a heap sort using a max heap.

#include <stdio.h>

int main()

int arr[10], no, i, j, c, heap_root, temp;

printf("Enter number of elements you want to insert:");

scanf("%d", &no);

printf("\nInput array values one by one : ");

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

scanf("%d", &arr[i]);

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

c = i;

do

heap_root = (c - 1) / 2;

/* to create MAX arr array */

if (arr[heap_root] < arr[c])

temp = arr[heap_root];

17
arr[heap_root] = arr[c];

arr[c] = temp;

c = heap_root;

} while (c != 0);

printf("Heap array : ");

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

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

for (j = no - 1; j >= 0; j--)

temp = arr[0];

arr[0] = arr[j];

arr[j] = temp;

heap_root = 0;

do

c = 2 * heap_root + 1;

if ((arr[c] < arr[c + 1]) && c < j-1)

c++;

if (arr[heap_root]<arr[c] && c<j)

temp = arr[heap_root];

18
arr[heap_root] = arr[c];

arr[c] = temp;

heap_root = c;

} while (c < j);

printf("\nSorted array : ");

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

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

printf("\n");

Output

Enter number of elements you want to insert:5

Input array values one by one: 34 23 56 45 67

Heap array: 67 56 34 23 45

Sorted array: 23 34 45 56 67

4. (a) Implement DFS/BFS for a connect graph.

Implementation of DFS

#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()

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

20
Output

Enter number of vertices:8

Enter adjacancy matrix of th graph:

10101011

0101 1011

01010101

10101010

11101001

11101110

01100101

00111010

Implementation of BFS

#include <stdbool.h>

#include <stdio.h>

#include <stdlib.h>

21
#define MAX_VERTICES 50

// This struct represents a directed graph using

// adjacency list representation

typedef struct Graph_t {

// No. of vertices

int V;

bool adj[MAX_VERTICES][MAX_VERTICES];

} Graph;

// Constructor

Graph* Graph_create(int V)

Graph* g = malloc(sizeof(Graph));

g->V = V;

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

for (int j = 0; j < V; j++) {

g->adj[i][j] = false;

return g;

// Destructor

void Graph_destroy(Graph* g) { free(g); }

22
// Function to add an edge to graph

void Graph_addEdge(Graph* g, int v, int w)

// Add w to v’s list.

g->adj[v][w] = true;

// Prints BFS traversal from a given source s

void Graph_BFS(Graph* g, int s)

// Mark all the vertices as not visited

bool visited[MAX_VERTICES];

for (int i = 0; i < g->V; i++) {

visited[i] = false;

// Create a queue for BFS

int queue[MAX_VERTICES];

int front = 0, rear = 0;

// Mark the current node as visited and enqueue it

visited[s] = true;

queue[rear++] = s;

while (front != rear) {

// Dequeue a vertex from queue and print it

s = queue[front++];

23
printf("%d ", s);

// Get all adjacent vertices of the dequeued

// vertex s.

// If an adjacent has not been visited,

// then mark it visited and enqueue it

for (int adjacent = 0; adjacent < g->V;

adjacent++) {

if (g->adj[s][adjacent] && !visited[adjacent]) {

visited[adjacent] = true;

queue[rear++] = adjacent;

// Driver code

int main()

// Create a graph

Graph* g = Graph_create(4);

Graph_addEdge(g, 0, 1);

Graph_addEdge(g, 0, 2);

Graph_addEdge(g, 1, 2);

Graph_addEdge(g, 2, 0);

24
Graph_addEdge(g, 2, 3);

Graph_addEdge(g, 3, 3);

printf("Following is Breadth First Traversal

starting from vertex 2 \n");

Graph_BFS(g, 2);

Graph_destroy(g);

return 0;

Output

Following is Breadth First Traversal starting from vertex 2

2031

(b) Implement Dijkstra’s shortest path algorithm using BFS

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

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

//pred[] stores the predecessor of each node

//count gives the number of nodes seen so far

//create the cost matrix

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

//initialize pred[],distance[] and visited[]

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

26
{

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;

//nextnode gives the node at minimum distance

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

if(distance[i]<mindistance&&!visited[i])

mindistance=distance[i];

nextnode=i;

//check if a better path exists through nextnode

visited[nextnode]=1;

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

if(!visited[i])

if(mindistance+cost[nextnode][i]<distance[i])

27
{

distance[i]=mindistance+cost[nextnode][i];

pred[i]=nextnode;

count++;

//print the path and distance of each node

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

if(i!=startnode)

printf("\nDistance of node%d=%d",i,distance[i]);

printf("\nPath=%d",i);

j=i;

do

j=pred[j];

printf("<-%d",j);

}while(j!=startnode);

Output

Enter no. of vertices:5

Enter the adjacency matrix:

28
15806

62793

20513

18102

86091

Enter the starting node:0

Distance of node1=5

Path=1<-0

Distance of node2=8

Path=2<-0

Distance of node3=9

Path=3<-2<-0

Distance of node4=6

Path=4<-0

5. (a) Write a program to implement Huffman’s algorithm

#include <stdio.h>

#include <stdlib.h>

// This constant can be avoided by explicitly

// calculating height of Huffman Tree

#define MAX_TREE_HT 100

// A Huffman tree node

struct MinHeapNode {

// One of the input characters

29
char data;

// Frequency of the character

unsigned freq;

// Left and right child of this node

struct MinHeapNode *left, *right;

};

// A Min Heap: Collection of

// min-heap (or Huffman tree) nodes

struct MinHeap {

// Current size of min heap

unsigned size;

// capacity of min heap

unsigned capacity;

// Array of minheap node pointers

struct MinHeapNode** array;

};

// A utility function allocate a new

// min heap node with given character

// and frequency of the character

struct MinHeapNode* newNode(char data, unsigned freq)

struct MinHeapNode* temp = (struct MinHeapNode*)malloc(sizeof(struct


MinHeapNode));

temp->left = temp->right = NULL;

30
temp->data = data;

temp->freq = freq;

return temp;

// A utility function to create

// a min heap of given capacity

struct MinHeap* createMinHeap(unsigned capacity)

struct MinHeap* minHeap= (struct MinHeap*)malloc(sizeof(struct MinHeap));

// current size is 0

minHeap->size = 0;

minHeap->capacity = capacity;

minHeap->array = (struct MinHeapNode**)malloc(

minHeap->capacity * sizeof(struct MinHeapNode*));

return minHeap;

// A utility function to

// swap two min heap nodes

void swapMinHeapNode(struct MinHeapNode** a,struct MinHeapNode** b)

struct MinHeapNode* t = *a;

*a = *b;

*b = t;

31
}

// The standard minHeapify function.

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

// A utility function to check

// if size of heap is 1 or not

32
int isSizeOne(struct MinHeap* minHeap)

return (minHeap->size == 1);

// A standard function to extract

// minimum value node from heap

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;

// A utility function to insert

// a new node to Min Heap

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;

33
}

minHeap->array[i] = minHeapNode;

// A standard function to build min heap

void buildMinHeap(struct MinHeap* minHeap)

int n = minHeap->size - 1;

int i;

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

minHeapify(minHeap, i);

// A utility function to print an array of size n

void printArr(int arr[], int n)

int i;

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

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

printf("\n");

// Utility function to check if this node is leaf

int isLeaf(struct MinHeapNode* root)

34
return !(root->left) && !(root->right);

// Creates a min heap of capacity

// equal to size and inserts all character of

// data[] in min heap. Initially size of

// min heap is equal to capacity

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;

// The main function that builds Huffman tree

struct MinHeapNode* buildHuffmanTree(char data[],int freq[], int size)

struct MinHeapNode *left, *right, *top;

// Step 1: Create a min heap of capacity

// equal to size. Initially, there are

// modes equal to size.

35
struct MinHeap* minHeap

= createAndBuildMinHeap(data, freq, size);

// Iterate while size of heap doesn't become 1

while (!isSizeOne(minHeap)) {

// Step 2: Extract the two minimum

// freq items from min heap

left = extractMin(minHeap);

right = extractMin(minHeap);

// Step 3: Create a new internal

// node with frequency equal to the

// sum of the two nodes frequencies.

// Make the two extracted node as

// left and right children of this new node.

// Add this node to the min heap

// '$' is a special value for internal nodes, not

// used

top = newNode('$', left->freq + right->freq);

top->left = left;

top->right = right;

insertMinHeap(minHeap, top);

// Step 4: The remaining node is the

// root node and the tree is complete.

36
return extractMin(minHeap);

// Prints huffman codes from the root of Huffman Tree.

// It uses arr[] to store codes

void printCodes(struct MinHeapNode* root, int arr[],int top)

// Assign 0 to left edge and recur

if (root->left) {

arr[top] = 0;

printCodes(root->left, arr, top + 1);

// Assign 1 to right edge and recur

if (root->right) {

arr[top] = 1;

printCodes(root->right, arr, top + 1);

// If this is a leaf node, then

// it contains one of the input

// characters, print the character

// and its code from arr[]

if (isLeaf(root)) {

printf("%c: ", root->data);

printArr(arr, top);

37
}

// The main function that builds a

// Huffman Tree and print codes by traversing

// the built Huffman Tree

void HuffmanCodes(char data[], int freq[], int size)

// Construct Huffman Tree

struct MinHeapNode* root

= buildHuffmanTree(data, freq, size);

// Print Huffman codes using

// the Huffman tree built above

int arr[MAX_TREE_HT], top = 0;

printCodes(root, arr, top);

// Driver code

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

38
Output

F: 0

C: 100

D: 101

A: 1100

B: 1101

E: 111

(b) Implement MST using Kruskal/Prim agorithm

Implement MST using Kruskal agorithm

#include <stdio.h>

#include <stdlib.h>

// Comparator function to use in sorting

int comparator(const void* p1, const void* p2)

const int(*x)[3] = p1;

const int(*y)[3] = p2;

return (*x)[2] - (*y)[2];

// Initialization of parent[] and rank[] arrays

void makeSet(int parent[], int rank[], int n)

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

39
parent[i] = i;

rank[i] = 0;

// Function to find the parent of a node

int findParent(int parent[], int component)

if (parent[component] == component)

return component;

return parent[component]

= findParent(parent, parent[component]);

// Function to unite two sets

void unionSet(int u, int v, int parent[], int rank[], int n)

// Finding the parents

u = findParent(parent, u);

v = findParent(parent, v);

if (rank[u] < rank[v]) {

parent[u] = v;

40
}

else if (rank[u] > rank[v]) {

parent[v] = u;

else {

parent[v] = u;

// Since the rank increases if

// the ranks of two sets are same

rank[u]++;

// Function to find the MST

void kruskalAlgo(int n, int edge[n][3])

// First we sort the edge array in ascending order

// so that we can access minimum distances/cost

qsort(edge, n, sizeof(edge[0]), comparator);

int parent[n];

int rank[n];

// Function to initialize parent[] and rank[]

makeSet(parent, rank, n);

// To store the minimun cost

41
int minCost = 0;

printf(

"Following are the edges in the constructed MST\n");

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

int v1 = findParent(parent, edge[i][0]);

int v2 = findParent(parent, edge[i][1]);

int wt = edge[i][2];

// If the parents are different that

// means they are in different sets so

// union them

if (v1 != v2) {

unionSet(v1, v2, parent, rank, n);

minCost += wt;

printf("%d -- %d = %d\n", edge[i][0],

edge[i][1], wt);

printf("Minimum Cost Spanning Tree: %d\n", minCost);

// Driver code

int main()

int edge[5][3] = { { 0, 1, 10 },

42
{ 0, 2, 6 },

{ 0, 3, 5 },

{ 1, 3, 15 },

{ 2, 3, 4 } };

kruskalAlgo(5, edge);

return 0;

Output

Followin are the edges in the constructed MST

2–3 =4

0–3= 5

0 – 1 = 10

Minimum Cost Spanning Tree: 19

Implement MST using Prim agorithm

#include <stdio.h>

#include <limits.h>

#define vertices 5 /*Define the number of vertices in the graph*/

/* create minimum_key() method for finding the vertex that has minimum key-value
and that is not added in MST yet */

int minimum_key(int k[], int mst[])

int minimum = INT_MAX, min,i;

/*iterate over all vertices to find the vertex with minimum key-value*/

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

43
if (mst[i] == 0 && k[i] < minimum )

minimum = k[i], min = i;

return min;

/* create prim() method for constructing and printing the MST.

The g[vertices][vertices] is an adjacency matrix that defines the graph for MST.*/

void prim(int g[vertices][vertices])

/* create array of size equal to total number of vertices for storing the MST*/

int parent[vertices];

/* create k[vertices] array for selecting an edge having minimum weight*/

int k[vertices];

int mst[vertices];

int i, count,edge,v; /*Here 'v' is the vertex*/

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

k[i] = INT_MAX;

mst[i] = 0;

k[0] = 0; /*It select as first vertex*/

parent[0] = -1; /* set first value of parent[] array to -1 to make it root of MST*/

for (count = 0; count < vertices-1; count++)

44
/*select the vertex having minimum key and that is not added in the MST yet
from the set of vertices*/

edge = minimum_key(k, mst);

mst[edge] = 1;

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

if (g[edge][v] && mst[v] == 0 && g[edge][v] < k[v])

parent[v] = edge, k[v] = g[edge][v];

/*Print the constructed Minimum spanning tree*/

printf("\n Edge \t Weight\n");

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

printf(" %d <-> %d %d \n", parent[i], i, g[i][parent[i]]);

int main()

int g[vertices][vertices] = {{0, 0, 3, 0, 0},

{0, 0, 10, 4, 0},

{3, 10, 0, 2, 6},

{0, 4, 2, 0, 1},

{0, 0, 6, 1, 0},

45
};

prim(g);

return 0;

Output

Edge Weight

3 <-> 1 4

0 <-> 2 3

2 <-> 3 2

3 <-> 4 1

6. (a) Write a program to implement Quick Sort algorithm

// Quick sort in C

#include <stdio.h>

// function to swap elements

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

int t = *a;

*a = *b;

*b = t;

// function to find the partition position

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

// select the rightmost element as pivot

int pivot = array[high];

46
// pointer for greater element

int i = (low - 1);

// traverse each element of the array

// compare them with the pivot

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

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

if (low < high) {

// find the pivot element such that

// elements smaller than pivot are on left of pivot

// elements greater than pivot are on right of pivot

47
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 data[] = {8, 7, 2, 1, 0, 9, 6};

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

printf("Unsorted Array\n");

printArray(data, n);

// perform quicksort on data

quickSort(data, 0, n - 1);

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

48
printArray(data, n);

Output

Unsorted Array

8 7 2 1 0 9 6

Sorted array in ascending order:

0 1 2 6 7 8 9

(b) Write a program on merge sort algorithm

// C program for Merge Sort

#include <stdio.h>

#include <stdlib.h>

// Merges two subarrays of arr[].

// First subarray is arr[l..m]

// Second subarray is arr[m+1..r]

void merge(int arr[], int l,int m, int r)

int i, j, k;

int n1 = m - l + 1;

int n2 = r - m;

// Create temp arrays

int L[n1], R[n2];

// Copy data to temp arrays

// L[] and R[]

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

L[i] = arr[l + i];

for (j = 0; j < n2; j++)

R[j] = arr[m + 1 + j];

// Merge the temp arrays back

// into arr[l..r]

// Initial index of first subarray

i = 0;

// Initial index of second subarray

j = 0;

// Initial index of merged subarray

k = l;

while (i < n1 && j < n2)

if (L[i] <= R[j])

arr[k] = L[i];

i++;

else

arr[k] = R[j];

j++;

50
}

k++;

// Copy the remaining elements

// of L[], if there are any

while (i < n1) {

arr[k] = L[i];

i++;

k++;

// Copy the remaining elements of

// R[], if there are any

while (j < n2)

arr[k] = R[j];

j++;

k++;

// l is for left index and r is

// right index of the sub-array

// of arr to be sorted

void mergeSort(int arr[],

51
int l, int r)

if (l < r)

// Same as (l+r)/2, but avoids

// overflow for large l and h

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

// Sort first and second halves

mergeSort(arr, l, m);

mergeSort(arr, m + 1, r);

merge(arr, l, m, r);

// UTILITY FUNCTIONS

// Function to print an array

void printArray(int A[], int size)

int i;

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

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

printf("\n");

// Driver code

52
int main()

int arr[] = {12, 11, 13, 5, 6, 7};

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

printf("Given array is \n");

printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

printf("\nSorted array is \n");

printArray(arr, arr_size);

return 0;

Output

Given array is

12 11 13 5 6 7

Sorted array is

5 6 7 11 12 13

7. Implement Strassen’s matrix multiplication algirithm

#include<stdio.h>

int main(){

int a[2][2], b[2][2], c[2][2], i, j;

int m1, m2, m3, m4 , m5, m6, m7;

printf("Enter the 4 elements of first matrix: ");

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

53
for(j = 0;j < 2; j++)

scanf("%d", &a[i][j]);

printf("Enter the 4 elements of second matrix: ");

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

for(j = 0;j < 2; j++)

scanf("%d", &b[i][j]);

printf("\nThe first matrix is\n");

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

printf("\n");

for(j = 0; j < 2; j++)

printf("%d\t", a[i][j]);

printf("\nThe second matrix is\n");

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

printf("\n");

for(j = 0;j < 2; j++)

printf("%d\t", b[i][j]);

m1= (a[0][0] + a[1][1]) * (b[0][0] + b[1][1]);

m2= (a[1][0] + a[1][1]) * b[0][0];

m3= a[0][0] * (b[0][1] - b[1][1]);

m4= a[1][1] * (b[1][0] - b[0][0]);

m5= (a[0][0] + a[0][1]) * b[1][1];

54
m6= (a[1][0] - a[0][0]) * (b[0][0]+b[0][1]);

m7= (a[0][1] - a[1][1]) * (b[1][0]+b[1][1]);

c[0][0] = m1 + m4- m5 + m7;

c[0][1] = m3 + m5;

c[1][0] = m2 + m4;

c[1][1] = m1 - m2 + m3 + m6;

printf("\nAfter multiplication using Strassen's algorithm \n");

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

printf("\n");

for(j = 0;j < 2; j++)

printf("%d\t", c[i][j]);

return 0;

Output

Enter the 4 elements of first matrix:

25

64

Enter the 4 elements of second matrix: 8 9

31

The first matrix is

2 5

6 4

55
The second matrix is

8 9

3 1

After multiplication using Strassen's algorithm

31 23

60 58

8. write down a proram to findout a solution for 0/1 knapsack problem

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

56
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

9. Using dynamic programming implement LCS

#include <stdio.h>

#include <string.h>

int i, j, m, n, LCS_table[20][20];

char S1[20] = "abcde", S2[20] = "defgh", b[20][20];

void lcsAlgo() {

57
m = strlen(S1);

n = strlen(S2);

// Filling 0's in the matrix

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

LCS_table[i][0] = 0;

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

LCS_table[0][i] = 0;

// Creating the mtrix in bottom-up way

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

for (j = 1; j <= n; j++) {

if (S1[i - 1] == S2[j - 1]) {

LCS_table[i][j] = LCS_table[i - 1][j - 1] + 1;

} else if (LCS_table[i - 1][j] >= LCS_table[i][j - 1]) {

LCS_table[i][j] = LCS_table[i - 1][j];

} else {

LCS_table[i][j] = LCS_table[i][j - 1];

int index = LCS_table[m][n];

char lcsAlgo[index + 1];

lcsAlgo[index] = '\0';

int i = m, j = n;

while (i > 0 && j > 0) {

58
if (S1[i - 1] == S2[j - 1]) {

lcsAlgo[index - 1] = S1[i - 1];

i--;

j--;

index--;

else if (LCS_table[i - 1][j] > LCS_table[i][j - 1])

i--;

else

j--;

// Printing the sub sequences

printf("S1 : %s \nS2 : %s \n", S1, S2);

printf("LCS: %s", lcsAlgo);

int main() {

lcsAlgo();

printf("\n");

Output

S1 : abcde

S2 : defgh

LCS: de

59
10. Findout the solution to the N-Queen problem

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

//function for printing the solution

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)

60
{

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

/*funtion to check conflicts

If no conflict for desired postion returns 1 otherwise returns 0*/

int place(int row,int column)

int i;

for(i=1;i<=row-1;++i)

//checking column and digonal conflicts

if(board[i]==column)

return 0;

else

if(abs(board[i]-column)==abs(i-row))

61
return 0;

return 1; //no conflicts

//function to check for proper positioning of queen

void queen(int row,int n)

int column;

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

if(place(row,column))

board[row]=column; //no conflicts so place queen

if(row==n) //dead end

print(n); //printing the board configuration

else //try queen with next position

queen(row+1,n);

62
Output

Enter number of Queens:4

Solution 1:

1 2 3 4

1 - Q - -

2 - - - Q

3 Q - - -

4 - - Q -

Solution 2:

1 2 3 4

1 - - Q -

2 Q - - -

3 - - - Q

4 - Q - -

63

You might also like