C++ Code
C++ Code
#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:
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
14
Node Inserted
13
4
Node Inserted
Deletion of BST
#include<stdio.h>
#include<stdlib.h>
struct node {
int key;
};
temp->key = item;
return temp;
if (root != NULL) {
inorder(root->left);
inorder(root->right);}}
5
/* A utility function to insert a new node with given key in BST */
if (node == NULL)
return newNode(key);
else
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. */
current = current->left;
return current;
6
/* Given a binary search tree and a key, this function deletes the key
// base case
if (root == NULL)
return root;
// to be deleted
else {
if (root->left == NULL) {
free(root);
return temp;
7
struct node *temp = root->left;
free(root);
return temp;
root->key = temp->key;
return root;
int main() {
50
/ \
30 70
/ \ / \
20 40 60 80 */
8
root = insert(root, 50);
inorder(root);
printf("\nDelete 20\n");
inorder(root);
printf("\nDelete 30\n");
inorder(root);
printf("\nDelete 50\n");
inorder(root);
return 0;
9
Output
20 30 40 50 60 70 80
Delete 20
30 40 50 60 70 80
Searching of BST
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int data;
};
if (*n == NULL) {
(*n) = (node*)malloc(sizeof(node));
(*n)->leftChildNode = NULL;
(*n)->rightChildNode = NULL;
(*n)->data = i;
10
}
else if ((*n)->data == i)
insertNode(i, &((*n)->rightChildNode));
else
insertNode(i, &((*n)->leftChildNode));
/* End of insertNode() */
if (*n == NULL)
else if((*n)->data == i)
printf("\nValue found!");
searchNode(i, &((*n)->rightChildNode));
else
searchNode(i, &((*n)->leftChildNode));
/* End of serachNode() */
11
/* The main() program begins */
int main()
do {
printf("\nChoice: ");
scanf("%d", &ch);
switch(ch) {
case 1:
scanf("%d", &num);
insertNode(num, &rootNode);
break;
case 2:
scanf("%d", &num);
searchNode(num, &rootNode);
break;
default:
exit(0);
12
}
printf("\nChoice: ");
scanf("%d", &num);
} while(num == 1);
return 0;
Output
1. Insert a node.
Choice: 1
Enter an element: 45
Choice: 1
1. Insert a node.
Choice: 1
Enter an element: 34
Choice: 1
13
1. Insert a node.
Choice: 2
Value found!
Choice: 2
Binary Search
#include <stdio.h>
int main()
scanf("%d",&n);
scanf("%d",&array[i]);
scanf("%d", &key);
low = 0;
high = n - 1;
mid = (low+high)/2;
14
while (low <= high) {
low = mid + 1;
break;
else
high = mid - 1;
return 0;
Output
Enter 5 integers
56 34 23 78 12
23 found at location 3
15
Linear Search
#include<stdio.h>
int main()
int a[20],i,x,n;
scanf("%d",&n);
for(i=0;i<n;++i)
scanf("%d",&a[i]);
scanf("%d",&x);
for(i=0;i<n;++i)
if(a[i]==x)
break;
if(i<n)
else
return 0;
Output
16
Enter array elements 45 34 28 65 49
#include <stdio.h>
int main()
scanf("%d", &no);
scanf("%d", &arr[i]);
c = i;
do
heap_root = (c - 1) / 2;
temp = arr[heap_root];
17
arr[heap_root] = arr[c];
arr[c] = temp;
c = heap_root;
} while (c != 0);
temp = arr[0];
arr[0] = arr[j];
arr[j] = temp;
heap_root = 0;
do
c = 2 * heap_root + 1;
c++;
temp = arr[heap_root];
18
arr[heap_root] = arr[c];
arr[c] = temp;
heap_root = c;
printf("\n");
Output
Heap array: 67 56 34 23 45
Sorted array: 23 34 45 56 67
Implementation of DFS
#include<stdio.h>
void DFS(int);
void main()
19
int i,j;
scanf("%d",&n);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
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
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
// 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;
g->adj[i][j] = false;
return g;
// Destructor
22
// Function to add an edge to graph
g->adj[v][w] = true;
bool visited[MAX_VERTICES];
visited[i] = false;
int queue[MAX_VERTICES];
visited[s] = true;
queue[rear++] = s;
s = queue[front++];
23
printf("%d ", s);
// vertex s.
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);
Graph_BFS(g, 2);
Graph_destroy(g);
return 0;
Output
2031
#include<stdio.h>
#include<conio.h>
#define MAX 10
int main()
int G[MAX][MAX],i,j,n,u;
scanf("%d",&n);
25
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
scanf("%d",&u);
dijkstra(G,n,u);
return 0;
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++)
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;
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])
27
{
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",i,distance[i]);
printf("\nPath=%d",i);
j=i;
do
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
Output
28
15806
62793
20513
18102
86091
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
#include <stdio.h>
#include <stdlib.h>
struct MinHeapNode {
29
char data;
unsigned freq;
};
struct MinHeap {
unsigned size;
unsigned capacity;
};
30
temp->data = data;
temp->freq = freq;
return temp;
// current size is 0
minHeap->size = 0;
minHeap->capacity = capacity;
return minHeap;
// A utility function to
*a = *b;
*b = t;
31
}
&& minHeap->array[left]->freq
< minHeap->array[smallest]->freq)
smallest = left;
&& minHeap->array[right]->freq
< minHeap->array[smallest]->freq)
smallest = right;
if (smallest != idx) {
swapMinHeapNode(&minHeap->array[smallest],
&minHeap->array[idx]);
minHeapify(minHeap, smallest);
32
int isSizeOne(struct MinHeap* minHeap)
--minHeap->size;
minHeapify(minHeap, 0);
return temp;
++minHeap->size;
int i = minHeap->size - 1;
i = (i - 1) / 2;
33
}
minHeap->array[i] = minHeapNode;
int n = minHeap->size - 1;
int i;
minHeapify(minHeap, i);
int i;
printf("%d", arr[i]);
printf("\n");
34
return !(root->left) && !(root->right);
minHeap->size = size;
buildMinHeap(minHeap);
return minHeap;
35
struct MinHeap* minHeap
while (!isSizeOne(minHeap)) {
left = extractMin(minHeap);
right = extractMin(minHeap);
// used
top->left = left;
top->right = right;
insertMinHeap(minHeap, top);
36
return extractMin(minHeap);
if (root->left) {
arr[top] = 0;
if (root->right) {
arr[top] = 1;
if (isLeaf(root)) {
printArr(arr, top);
37
}
// Driver code
int main()
return 0; }
38
Output
F: 0
C: 100
D: 101
A: 1100
B: 1101
E: 111
#include <stdio.h>
#include <stdlib.h>
39
parent[i] = i;
rank[i] = 0;
if (parent[component] == component)
return component;
return parent[component]
= findParent(parent, parent[component]);
u = findParent(parent, u);
v = findParent(parent, v);
parent[u] = v;
40
}
parent[v] = u;
else {
parent[v] = u;
rank[u]++;
int parent[n];
int rank[n];
41
int minCost = 0;
printf(
int wt = edge[i][2];
// union them
if (v1 != v2) {
minCost += wt;
edge[i][1], wt);
// 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
2–3 =4
0–3= 5
0 – 1 = 10
#include <stdio.h>
#include <limits.h>
/* create minimum_key() method for finding the vertex that has minimum key-value
and that is not added in MST yet */
/*iterate over all vertices to find the vertex with minimum key-value*/
43
if (mst[i] == 0 && k[i] < minimum )
return min;
The g[vertices][vertices] is an adjacency matrix that defines the graph for MST.*/
/* create array of size equal to total number of vertices for storing the MST*/
int parent[vertices];
int k[vertices];
int mst[vertices];
k[i] = INT_MAX;
mst[i] = 0;
parent[0] = -1; /* set first value of parent[] array to -1 to make it root of MST*/
44
/*select the vertex having minimum key and that is not added in the MST yet
from the set of vertices*/
mst[edge] = 1;
int main()
{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
// Quick sort in C
#include <stdio.h>
int t = *a;
*a = *b;
*b = t;
46
// pointer for greater element
i++;
swap(&array[i], &array[j]);
return (i + 1);
47
int pi = partition(array, low, high);
quickSort(array, pi + 1, high);
printf("\n");
// main function
int main() {
printf("Unsorted Array\n");
printArray(data, n);
quickSort(data, 0, n - 1);
48
printArray(data, n);
Output
Unsorted Array
8 7 2 1 0 9 6
0 1 2 6 7 8 9
#include <stdio.h>
#include <stdlib.h>
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
49
for (i = 0; i < n1; i++)
// into arr[l..r]
i = 0;
j = 0;
k = l;
arr[k] = L[i];
i++;
else
arr[k] = R[j];
j++;
50
}
k++;
arr[k] = L[i];
i++;
k++;
arr[k] = R[j];
j++;
k++;
// of arr to be sorted
51
int l, int r)
if (l < r)
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
// UTILITY FUNCTIONS
int i;
printf("\n");
// Driver code
52
int main()
printArray(arr, arr_size);
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
#include<stdio.h>
int main(){
53
for(j = 0;j < 2; j++)
scanf("%d", &a[i][j]);
scanf("%d", &b[i][j]);
printf("\n");
printf("%d\t", a[i][j]);
printf("\n");
printf("%d\t", b[i][j]);
54
m6= (a[1][0] - a[0][0]) * (b[0][0]+b[0][1]);
c[0][1] = m3 + m5;
c[1][0] = m2 + m4;
c[1][1] = m1 - m2 + m3 + m6;
printf("\n");
printf("%d\t", c[i][j]);
return 0;
Output
25
64
31
2 5
6 4
55
The second matrix is
8 9
3 1
31 23
60 58
#include<stdio.h>
if(a>b){
return a;
} else {
return b;
int i, w;
int knap[n+1][W+1];
if (i==0 || w==0)
knap[i][w] = 0;
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 W = 50;
int n = sizeof(val)/sizeof(val[0]);
return 0;
Output
The solution is : 65
#include <stdio.h>
#include <string.h>
int i, j, m, n, LCS_table[20][20];
void lcsAlgo() {
57
m = strlen(S1);
n = strlen(S2);
LCS_table[i][0] = 0;
LCS_table[0][i] = 0;
} else {
lcsAlgo[index] = '\0';
int i = m, j = n;
58
if (S1[i - 1] == S2[j - 1]) {
i--;
j--;
index--;
i--;
else
j--;
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;
scanf("%d",&n);
queen(1,n);
return 0;
void print(int n)
int i,j;
printf("\n\nSolution %d:\n\n",++count);
for(i=1;i<=n;++i)
printf("\t%d",i);
for(i=1;i<=n;++i)
60
{
printf("\n\n%d",i);
if(board[i]==j)
else
int i;
for(i=1;i<=row-1;++i)
if(board[i]==column)
return 0;
else
if(abs(board[i]-column)==abs(i-row))
61
return 0;
int column;
for(column=1;column<=n;++column)
if(place(row,column))
queen(row+1,n);
62
Output
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