Mukesh Ds Practical File
Mukesh Ds Practical File
DATA STRUCTURES
LABORATORY RECORD
Certified that this is a bonafide record of work done by Mr. Mukesh Kumar in
the Data Structures Laboratory of the Department of Computer Applications,
Cochin University of Science and Technology.
2. Create a C Program to read 3 integer values, find the largest among them 5-6
5. Write a c program to read a string and count the number of vowels, 8-10
consonants and spaces in it.
6. Using structure, write a program to read and print data of n employees 10-11
(Name, EmployeeId and Salary)
10. Construct binary search trees to perform insertion, deletion, search. 15-20
11. Apply Queue and stack in Breadth First Search and Depth First Search 20-25
respectively
12. Write a program to create a binary search tree and find the number of 25-30
leaf nodes
13. Create a binary search tree with the following operations: 30-35
i)Insert a new node
ii)Inorder traversal
iii)Preorder traversal
iv)Postorder traversal
3
v) Delete a node.
14. Design, develop, and execute a program in C to create a max heap and 35-39
perform the following operations
i)Insertion
ii)Deletion
iii)Print Largest Value
15. Write a program to implement Depth First Search (DFS) graph traversal 39-43
methods.
16. Write a program to implement Breadth First Search (BFS) graph 43-47
traversal methods
17. Create a text file containing the name, height, weight of the students in a 47-53
class. Perform Quick sort and Merge sort on this data and store the
resultant data in two separate files. Also write the time taken by the two
sorting methods into the respective files. Sony Mathew 5.5 60 Arun
Sajeev 5.7 58 Rajesh Kumar 6.1 70
18. Write a program to sort a set of numbers using Heap sort and find a 53-57
particular number from the sorted set using Binary Search.
19. Implement a Hash table using Chaining method. Let the size of hash 57-61
table be 10 so that the index varies from 0 to 9.
20. Implement a Hash table that uses Linear Probing for collision resolution 61-66
4
1. Write a C program to evaluate the arithmetic expression ((a -b / c * d + e) * (f +g))
and display its solution.
#include <stdio.h>
int main(){
int a, b, c, d, e, f, g, result;
printf("Enter variable to evaluate((a-b/c*d+e)*(f +g))\n");
printf("Enter a, b, c, d, e, f, g : ");
scanf("%d %d %d %d %d %d %d", &a, &b, &c, &d, &e, &f, &g);
if(c == 0)
printf("Zero Division Error !\n");
else{
result = (a - ((b / c) * d) + e) * (f + g);
printf("(a -b / c * d + e) * (f +g) = %d\n", result);
}
return 0;
}
Output :
Enter variable to evaluate((a -b / c * d + e) * (f +g))
Enter a, b, c, d, e, f, g : 10 10 5 2 4 5 6
(a -b / c * d + e) * (f +g) = 110
2. Create a C Program to read 3 integer values, find the largest among them.
5
3. Otherwise check if b>a and b>c : if True print(“b” is largest).
4. Otherwise check if c>a and c>b : if True print(“c” is largest).
5. Exit
Source Code :
#include <stdio.h>
int main(){
int a, b, c, max;
printf("Enter num1, num2, num3 to find largest among them :
");
scanf("%d %d %d", &a, &b, &c);
if(a>b && a>c)
printf("'a' = %d is the largest no.\n", a);
else if(b>a && b>c)
printf("'b' = %d is the largest no.\n", b);
else if(c>a && c>b)
printf("'c' = %d is the largest no.\n", c);
return 0;
}
Output :
Enter num1, num2, num3 to find largest among them : 10 20 15
'b' = 20 is the largest no.
6
#define True 1
#define False 0
int main(){
int num, i, isPrime;
printf("Enter a natural no. to check if it is prime : ");
scanf("%d", &num);
if(num<=0)
printf("Negative and zero not allowed!\n");
else if(num == 1)
printf("1 is Unique number");
else{
isPrime = True;
for(i = 2; i<num; i++){
if(num%i == 0){
isPrime = False;
break;}
}
if(isPrime)
printf("%d is a prime no.\n", num);
else
printf("%d is not a prime no.\n", num);
}
return 0;
}
Output :
Enter a natural no. to check if it is prime : 17
17 is a prime no.
7
12. numCopy = numCopy/10.
13. Check numCopy == num
If true : print(“An armstrong number”)
14. Otherwise print(“Not an Armstrong number”)
15. Exit
*power(base, exp)
1. Declare variable ‘i’ and ‘result’ as int.
2. Assign ‘result’ = 1 and ‘i’ = 1.
3. Repeat Steps 4 to 5 until i <= exp
4. result = result * base
5. Increment i by 1.
6. Return result.
Source Code :
#include <stdio.h>
int power(int base, int exp);
int main(){
int num, numCopy, cntDigits, rem, sum, i;
printf("Enter a no. to check if it is Armstrong : ");
scanf("%d", &num);
numCopy = num;
for(cntDigits = 0; numCopy > 0; numCopy /= 10, cntDigits++);
for(sum = 0, numCopy = num; numCopy; numCopy/=10){
rem = numCopy%10; sum += power(rem, cntDigits);}
if(sum == num)
printf("%d is an Armstrong Number\n", num);
else
printf("%d is not an Armstrong Number\n", num);
return 0;
}
int power(int base, int exp){
int res;
for(res = 1; exp; res = res*base, exp--);
return res;}
Output :
Enter a no. to check if it is Armstrong : 153
153 is an Armstrong Number
5. Write a c program to read a string and count the number of vowels, consonants
and spaces in it.
8
1. Declare an array of characters ‘str[100]’.
2. Declare variables ‘i’, ‘cntVowels’, ‘cntSpaces’ and ‘cntCons’ as int.
3. Read ‘str’.
4. Assign cntVowels = cntSpaces = cntCons = 0.
5. Assign i = 0;
6. Repeat steps 7 to 11 until str[i] is not the last character of the string.
7. Check str[i] is a character or a space
If true then proceed
Otherwise go to step no. 11.
8. Check str[i] to be a vowel if true increment cntVowels by 1.
9. Otherwise check str[i] to be a space, if true increment cntSpaces by 1.
10. Otherwise increment cntCons by 1.
11. Increment i by 1.
12. Print the count of vowels, consonants and spaces.
Source Code :
#include <stdio.h>
int main(){
char str[100];
int i, cntVowels, cntSpaces, cntCons;
printf("Enter a string to count vowels, consonants and
spaces : ");
scanf("%[^\n]s", str);
cntVowels = cntSpaces = cntCons = 0;
for(i = 0; str[i] != '\0'; i++)
{
if((str[i] >= 65 && str[i] <= 90) || (str[i] >= 97 &&
str[i] <= 122) || str[i] == ' ')
{
switch(str[i]){
case 'a' : case 'e' : case 'i' : case 'o' : case
'u' : case 'A' : case 'E' : case 'I' : case 'O' : case 'U' :
cntVowels++;break;
case ' ' : cntSpaces++;break;
default : cntCons++;
}}
}
printf("No. of vowels : %d\n", cntVowels);
printf("No. of consonants : %d\n", cntCons);
printf("No. of spaces : %d\n", cntSpaces);
return 0;
}
Output :
9
Enter a string to count vowels, consonants and spaces : The
quick brown fox jumped over the lazy dog.
No. of vowels : 12
No. of consonants : 24
No. of spaces : 8
6. Using structure, write a program to read and print data of n employees (Name,
EmployeeId and Salary)
10
printf("Employee Id : ");
scanf("%s", (emp+i)->emp_Id);
printf("Employee Salary : ");
scanf("%lf", &((emp+i)->emp_salary));
}
for(i = 0; i<n; i++){
printf("\n---Employee %d Details---\n", i+1);
printf("NAME : %s\n", (emp+i)->emp_name);
printf("ID : %s\n", (emp+i)->emp_Id);
printf("SALARY : %lf\n", (emp+i)->emp_salary);
}
free(emp);
return 0;
}
Output :
Enter no. of Employees : 3 ---Employee 1 Details---
NAME : Rama
___Fill in Employee 1 ID : e001
details___ SALARY : 10000.000000
Employee Name : Rama
Employee Id : e001 ---Employee 2 Details---
Employee Salary : 10000.00 NAME : Krishna
ID : e002
___Fill in Employee 2 SALARY : 20000.200000
details___
Employee Name : Krishna ---Employee 3 Details---
Employee Id : e002 NAME : Hari
Employee Salary : 20000.20 ID : e003
SALARY : 12000.200000
___Fill in Employee 3
details___
Employee Name : Hari
Employee Id : e003
Employee Salary : 12000.20
11
3. Assign firstTerm = 0, secondTerm = 1 and currentTerm = 1.
4. Call genFibSeries(firstTerm, secondTerm, currentTerm, n).
genFibSeries(first, second, current, n)
1. Check current <= n
If true : print(first)
Increment current by 1
Class genFibSeries(second, first+second, current, n)
2. Otherwise return.
Source Code :
#include <stdio.h>
void genFibSeries(int firstTerm, int SecondTem, int currTerm,
int nTerms);
int main(){
int n, firstTerm, secondTerm, currTerm;
printf("Enter no. of terms to generate Fibonacci Series :
");
scanf("%d", &n);
firstTerm = 0; secondTerm = 1; currTerm = 1;
genFibSeries(firstTerm, secondTerm, currTerm, n);
return 0;
}
void genFibSeries(int first, int second, int currTerm, int
nTerms){
if(currTerm <= nTerms){
printf("%d\t", first);
genFibSeries(second, first+second, currTerm+1, nTerms);
}}
Output :
Enter no. of terms to generate Fibonacci Series : 10
0 1 1 2 3 5 8 13
21 34
1. Declare num.
12
2. Read num.
3. Call factorial()
4. Call recFactorial()
5. Exit
factorial(num)
1. Declare i, fact.
2. Assign fact = 1 and i = 1.
3. Repeat steps 4 to 5 until i<=num
4. Fact = fact * i
5. Increment i by 1
6. Print fact.
recFactorial(num)
1. Check num <= 1 if true return 1
2. Otherwise return(num * recFactorial(num-1))
Source Code :
#include <stdio.h>
int factorial(int);
int recFactorial(int);
int main(){
int num;
printf("Enter non-negative integer to find factorial : ");
scanf("%d", &num);
if(num < 0)
printf("Factorial doesn't exists!\n");
else{
printf("Factorial Value\n");
printf("From Non-Recursive function : %d\n",
factorial(num));
printf("From Recursive function : %d\n",
recFactorial(num));
}
return 0;
}
int factorial(int num){
int fact=1;
for(; num>1; fact *= num, num--);
return fact;
}
int recFactorial(int num){
return(num > 1 ? num * recFactorial(num-1) : 1);
}
Output :
13
Enter non-negative integer to find factorial : 5
Factorial Value
From Non-Recursive function : 120
From Recursive function : 120
14
printf("num1 = %d, num2 = %d\n", num1, num2);
return 0;
}
int add(int *num1, int *num2){
return *num1 + *num2;
}
void swap(int *num1, int *num2){
int temp;
temp = *num1; *num1 = *num2; *num2 = temp;
}
Output :
Enter numbers for swapping and adding
Enter num1 : 20
Enter num2 : 40
Addition result : 60
Before Swapping
num1 = 20, num2 = 40
After Swapping
num1 = 40, num2 = 20
10. Construct binary search trees to perform insertion, deletion, and search.
15
V. Exit. Go to last step.
7. Exit
Insert(node, data)
1. If node == NULL : return a newnode with data as ‘data’
2. Otherwise if data < root->data : call insert(node->left, data).
3. Otherwise if data > root->data : call insert(node->right, data).
4. Exit
Delete(root, data)
1. If root === NULL : return ‘data not found’.
2. Otherwise if data < root->data : call delete(node->left, data)
3. Otherwise if data > root->data : call delete(node->right, data)
4. Otherwise if :
a.if root->left = NULL. struct NODE *temp = root->right. free(root). Return temp
b.if root->right = NULL. struct NODE *temp = root->left. free(root). Return temp
c.else temp = inorderSuccessor of root. Exchange the values of root and temp.
Delete inorder successor
Return root.
5. Exit
Search(root, data)
1. Repeat steps 2 to till root != NULL.
2. If data < root->data : root = root->left
3. Otherwise data > root->data : root->right
4. Otherwise print(“data found”)
5. Exit
Source Code :
#include <stdio.h>
#include <stdlib.h>
struct NODE{
struct NODE *left, *right;
int data;
};
struct NODE * insertNode(struct NODE *, int);
struct NODE * createNode(int);
int searchNode(struct NODE *, int);
void inorder(struct NODE *);
struct NODE * deleteNode(struct NODE *, int);
struct NODE * inorderSuccesor(struct NODE *);
int main(){
struct NODE *root;
int ch, data;
16
root = NULL;
while(1){
printf("\n1. Insert\n2. Delete\n3. Search\n4.
Display(Inorder Traversal)\n5. Exit");
printf("\nC H O O S E : ");
scanf("%d", &ch);
switch(ch){
case 1 :
printf("Enter the value to insert : ");
scanf("%d", &data);
root = insertNode(root, data);
printf("%d inserted...\n", data);
break;
case 2 :
if(root == NULL)
printf("Empty BST...\n");
else{
printf("Enter the data to delete : ");
scanf("%d", &data);
root = deleteNode(root, data);
}
break;
case 3 :
if(root == NULL)
printf("Empty BST...\n");
else{
printf("Enter the element to search : ");
scanf("%d", &data);
if(searchNode(root, data))
printf("%d found...\n", data);
else
printf("%d not found...\n", data);
}
break;
case 4 :
if(root == NULL)
printf("Empty BST...\n");
else{
printf("Inorder Traversal : ");
inorder(root);
printf("\n");
}
break;
case 5 : exit(0);
default : printf("\n! INVALID CHOICE !\n");
}}
return 0;
17
}
struct NODE * insertNode(struct NODE *root, int data){
if(root == NULL)
return(createNode(data));
if(data == root->data)
printf("Duplicate(%d) not allowed...\n", data);
if(data < root->data)
root->left = insertNode(root->left, data);
else if(data > root->data)
root->right = insertNode(root->right, data);
return root;
}
int searchNode(struct NODE *root, int data){
while(root != NULL){
if(data < root->data)
root = root->left;
else if(data > root->data)
root = root->right;
else
return 1;
}
return 0;
}
void inorder(struct NODE *root){
if(root != NULL) {
inorder(root->left);
printf("%d\t", root->data);
inorder(root->right);
}
}
struct NODE *createNode(int data){
struct NODE *newNode;
newNode = (struct NODE *) malloc(sizeof(struct NODE));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
struct NODE * inorderSuccessor(struct NODE * root){
if(root->left == NULL)
return root;
return (inorderSuccessor(root->left));
}
struct NODE * deleteNode(struct NODE *root, int data){
struct NODE *temp;
if(root == NULL)
printf("%d not found...\n", data);
else if(data < root->data)
18
root->left = deleteNode(root->left, data);
else if(data > root->data)
root->right = deleteNode(root->right, data);
else{
if(root->left == NULL){
temp = root->right;
free(root);
return temp;
}
else if(root->right == NULL){
temp = root->left;
free(root);
return temp;
}
else{
temp = inorderSuccessor(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
printf("%d deleted...\n", data);
}
return root;
}
Output :
1. Insert 1. Insert
2. Delete 2. Delete
3. Search 3. Search
4. Display(Inorder Traversal) 4. Display(Inorder Traversal)
5. Exit 5. Exit
C H O O S E : 1 C H O O S E : 4
Enter the value to insert : 50 Inorder Traversal : 5 25
50 inserted... 50 75 80
1. Insert 1. Insert
2. Delete 2. Delete
3. Search 3. Search
4. Display(Inorder Traversal) 4. Display(Inorder Traversal)
5. Exit 5. Exit
C H O O S E : 1 C H O O S E : 3
Enter the value to insert : 25 Enter the element to search :
25 inserted... 25
25 found...
19
1. Insert
2. Delete 1. Insert
3. Search 2. Delete
4. Display(Inorder Traversal) 3. Search
5. Exit 4. Display(Inorder Traversal)
C H O O S E : 1 5. Exit
Enter the value to insert : 75 C H O O S E : 2
75 inserted... Enter the data to delete : 25
1. Insert 1. Insert
2. Delete 2. Delete
3. Search 3. Search
4. Display(Inorder Traversal) 4. Display(Inorder Traversal)
5. Exit 5. Exit
C H O O S E : 1 C H O O S E : 4
Enter the value to insert : 5 Inorder Traversal : 5 50
5 inserted... 75 80
1. Insert 1. Insert
2. Delete 2. Delete
3. Search 3. Search
4. Display(Inorder Traversal) 4. Display(Inorder Traversal)
5. Exit 5. Exit
C H O O S E : 1 C H O O S E : 5
Enter the value to insert : 80
80 inserted...
11. Apply Queue and stack in Breadth First Search and Depth First Search
respectively
Objective: To understand the concepts of Queue, Stack, Breadth First Search and Depth
First Search
Algorithm:
1. Declare a struct NODE with fields data as integer, next as struct node *.
2. Create a stack, queue and a visited array.
3. Get the graph.
4. Apply bfs(). Apply dfs()
5. Exit.
20
dfs(graph, vertex v) :
1. If the vertex v is not visited print ‘v’.
2. Repeat steps 3 to 4 until all the adjacent vertex are not visited.
3. Explore the adjacent vertices to ‘v’.
4. If adjacent vertex is not visited : push ‘v’ in the stack.Call dfs(graph, adjacent
vertex)
5. If stack is not empty : dfs(pop the stack)
6. Exit
bfs(graph, vertex v) :
1. If the vertex v is not visited print ‘v’.
2. Repeat the steps 3 to 4 until all the adjacent vertices are not visited.
3. Explore the adjacent vertices to ‘v’.
4. If adjacent vertex is not visited : push ‘adjacent vertex’ to queue.
5. If queue is not empty apply bfs(dequeue())
6. Exit
Source Code :
#include <stdio.h>
#include <stdlib.h>
struct NODE{
int data;
struct NODE *next; };
struct NODE *top;
struct NODE *front, *rear;
void displayAdjMat(int **graph);
void dfs(int **graph, int);
void bfs(int **graph, int);
int n, *visited;
int main(){
int i, **graph, edge, vertex;
char ch;
printf("Enter no. of vertices : ");
scanf("%d", &n);
visited = (int *) calloc(n, sizeof(int));
graph = (int **) calloc(n, sizeof(int *));
for(i = 0; i<n; i++)
*(graph + i) = (int *) calloc(n, sizeof(int));
for(vertex = 0; vertex<n; vertex++){
printf("\nLink Vertex %d(y/n) : ", vertex);
scanf(" %c", &ch);
while((ch == 'y') || (ch == 'Y')){
do{
printf("Vertex no.(0 - %d) : ", n-1);
scanf("%d", &edge);
21
}while((edge<0) || (edge>=n));
graph[vertex][edge] = 1;
printf("Link More(y/n) : ");
scanf(" %c", &ch);
}
}
displayAdjMat(graph);
do{
for(i = 0; i<n; i++)
visited[i] = 0;
printf("Choose starting vertex for DFS : ");
scanf("%d", &vertex);
dfs(graph, vertex);
for(i = 0; i<n; i++)
visited[i] = 0;
printf("Choose starting vertex for BFS : ");
scanf("%d", &vertex);
bfs(graph, vertex);
printf("Traverse again(y/n) : ");
scanf(" %c", &ch);
} while (ch == 'y' || ch == 'Y');
return 0;
}
void displayAdjMat(int **graph){
int i, j;
printf("\n...Adjacency Matrix...\n");
for(i = 0; i<n; i++)
printf("\t%d", i);
printf("\n");
for(i = 0; i<n; i++){
printf("%d\t", i);
for(j = 0; j<n; j++)
printf("%d\t", graph[i][j]);
printf("\n");
}
}
void push(int data){
struct NODE * temp;
temp = (struct NODE *) malloc(sizeof(struct NODE));
temp->data = data;
temp->next = top;
top = temp;
}
int pop(){
struct NODE *temp;
int data;
if(top == NULL)
22
return -1;
data = top->data;
top = top->next;
return data;
}
void enqueue(int data){
struct NODE *temp;
temp = (struct NODE *) malloc(sizeof(struct NODE));
temp->data = data;
temp->next = NULL;
if(front == NULL)
front = rear = temp;
else{
rear->next = temp;
rear = temp;
}
}
int dequeue(){
int data;
if(front == NULL)
return -1;
data = front->data;
if(front == rear)
front = rear = NULL;
else
front = front->next;
return data;
}
void dfs(int **graph, int v){
int i, data;
if(visited[v] == 0){
printf("%d\t", v);
visited[v] = 1;
}
for(i = 0; i<n; i++){
if(graph[v][i] == 1 && visited[i] == 0){
visited[i] = 1;
printf("%d\t", i);
push(v);
dfs(graph, i);
}
}
data = pop();
if(data != -1)
dfs(graph, data);
}
void bfs(int **graph, int v){
23
int i, data;
if(visited[v] == 0){
visited[v] = 1;
printf("%d\t", v);
enqueue(v);
}
for(i = 0; i<n; i++){
if(graph[v][i] == 1 && visited[i] == 0) {
visited[i] = 1;
printf("%d\t", i);
enqueue(i);
}
}
data = dequeue();
if(data != -1)
bfs(graph, data);
}
Output :
Enter no. of vertices : 4
...Adjacency Matrix...
0 1 2 3
0 0 0 0 1
24
1 0 0 0 1
2 0 0 0 1
3 1 1 1 0
Choose starting vertex for DFS : 3
3 0 1 2
Choose starting vertex for BFS : 1
1 3 0 2
Traverse again(y/n) : n
12. Write a program to create a binary search tree and find the number of leaf
nodes
25
1.
If root === NULL : return ‘data not found’.
2.
Otherwise if data < root->data : call delete(node->left, data)
3.
Otherwise if data > root->data : call delete(node->right, data)
4.
Otherwise if :
a.if root->left = NULL. struct NODE *temp = root->right. free(root). Return temp
b.if root->right = NULL. struct NODE *temp = root->left. free(root). Return temp
c.else temp = inorderSuccessor of root. Exchange the values of root and temp.
Delete inorder successor
Return root.
5. Exit
countLeafNode(root)
1. If root != NULL then proceed otherwise return
2. Call countLeafNode(root->left)
3. If root is a leaf node: Increment a counter
4. Call countLeafNode(root->right)
5. Return counter
Source Code :
#include <stdio.h>
#include <stdlib.h>
struct NODE{
struct NODE *left,*right;
int data;};
struct NODE * create(int);
struct NODE * insert(struct NODE *, int);
struct NODE * delete(struct NODE *, int);
struct NODE * inorderSuccessor(struct NODE *);
int search(struct NODE *, int);
int cntLeaf(struct NODE *);
void inorder(struct NODE *);
int cnt = 0;
int main()
{
struct NODE *root;
int ch, data;
root = NULL;
while(1){
printf("\n1. Insert\n2. Deletion\n3. Search\n4.
Display(Inorder Traversal)\n5. Count Leaf\n6. Exit\nC H O O S E
: ");
scanf("%d", &ch);
switch(ch){
case 1 :
26
printf("Enter data : ");
scanf("%d", &data);
root = insert(root, data);
printf("%d insertd...\n", data);
Break;
case 2 :
if(root == NULL)
printf("Empty BST...\n");
else{
printf("Enter data : ");
scanf("%d", &data);
root = delete(root, data);
}
break;
case 3 :
if(root == NULL)
printf("Empty BST...\n");
else{
printf("Enter the data to search : ");
scanf("%d", &data);
if(search(root, data))
printf("%d found...\n", data);
else
printf("%d not found...\n", data);
}
break;
case 4 :
printf("\nDisplay : ");
inorder(root);
break;
case 5 :
printf("No. of leaf node : %d\n",
cntLeaf(root));
case 6 : exit(0);
default : printf("\n! INVALID CHOICE !\n");
}
}
return 0;
}
struct NODE * create(int data){
struct NODE *newNode;
newNode = (struct NODE *) malloc(sizeof(struct NODE));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
struct NODE * insert(struct NODE *root, int data){
27
if(root == NULL)
return(create(data));
if(data < root->data)
root->left = insert(root->left, data);
else if(data > root->data)
root->right = insert(root->right, data);
return root;
}
void inorder(struct NODE *root){
if(root != NULL){
inorder(root->left);
printf("%d\t", root->data);
inorder(root->right);
}
}
struct NODE * delete(struct NODE *root, int data){
struct NODE *temp;
if(root == NULL)
printf("%d not found...\n", data);
else if(data == root->data){
if(root->left == NULL){
temp = root->right;
free(root);
return(temp);
}
else if(root->right == NULL){
temp = root->left;
free(root); return temp;
}
temp = inorderSuccessor(root->right);
root->data = temp->data;
root->right = delete(root->right, temp->data);
}
else if(data > root->data)
root->right = delete(root->right, data);
else
root->left = delete(root->left, data);
return root;
}
struct NODE * inorderSuccessor(struct NODE *root){
if(root->left == NULL)
return(root);
return(inorderSuccessor(root->left));
}
int cntLeaf(struct NODE *root){
if(root != NULL){
cntLeaf(root->left);
28
if(root->left == NULL && root->right == NULL)
cnt++;
cntLeaf(root->right);
}
return cnt;
}
int search(struct NODE * root, int data){
while(root != NULL){
if(data < root->data)
root = root->left;
else if(data > root->data)
root = root->right;
else
return 1;
}
return 0;
}
Output :
1. Insert
2. Deletion 1. Insert
3. Search 2. Deletion
4. Display(Inorder Traversal) 3. Search
5. Count Leaf 4. Display(Inorder Traversal)
6. Exit 5. Count Leaf
C H O O S E : 1 6. Exit
Enter data : 50 C H O O S E : 1
50 insertd... Enter data : 60
60 insertd...
1. Insert
2. Deletion 1. Insert
3. Search 2. Deletion
4. Display(Inorder Traversal) 3. Search
5. Count Leaf 4. Display(Inorder Traversal)
6. Exit 5. Count Leaf
C H O O S E : 1 6. Exit
Enter data : 20 C H O O S E : 1
20 insertd... Enter data : 70
70 insertd...
1. Insert
2. Deletion 1. Insert
3. Search 2. Deletion
29
4. Display(Inorder Traversal) 3. Search
5. Count Leaf 4. Display(Inorder Traversal)
6. Exit 5. Count Leaf
C H O O S E : 1 6. Exit
Enter data : 30 C H O O S E : 5
30 inserted... No. of leaf node : 2
Objective: To understand the concepts of Queue, Stack, Breadth First Search and Depth
First Search .
Algorithm:
1. Declare ‘struct NODE’ with fields:
I. struct NODE pointer left, right.
II. integer ‘data’
2. Declare a struct NODE pointer ‘root’, integer ‘ch’ and ‘data’.
3. Assign root = NULL in the beginning.
4. Repeat steps 5 to 6 infinitely till user exits:
5. Read ‘ch’.
6. Check ch:
I . if ch == 1 :
Read ‘data’. Call insert()
II. if ch == 2 :
Read ‘data’. Call delete()
III. if ch == 3 :
Read ‘data’. Call search()
IV. if ch == 4 :
call inorder()
V. Exit. Go to last step.
7. Exit
Insert(node, data)
1. If node == NULL : return a newnode with data as ‘data’
2. Otherwise if data < root->data : call insert(node->left, data).
3. Otherwise if data > root->data : call insert(node->right, data).
4. Exit
30
Delete(root, data)
1. If root === NULL : return ‘data not found’.
2. Otherwise if data < root->data : call delete(node->left, data)
3. Otherwise if data > root->data : call delete(node->right, data)
4. Otherwise if :
a.if root->left = NULL. struct NODE *temp = root->right. free(root). Return temp
b.if root->right = NULL. struct NODE *temp = root->left. free(root). Return temp
c.else temp = inorderSuccessor of root. Exchange the values of root and temp.
Delete inorder successor
Return root.
5. Exit
Preorder(root)
1. If root != NULL then proceed otherwise return
2. Print root -> data.
3. Call preorder(root->left)
4. Call preorder(root->right)
5. Return.
Inorder(root)
1. If root != NULL then proceed otherwise return
2. Call inorder(root->left)
3. Print root->data.
4. Call inorder(root->right)
5. Return.
Postorder(root)
1. If root != NULL then proceed otherwise return
2. Call postorder(root->left)
3. Call postorder(root->right)
4. Print root->data
5. Return.
Source Code :
#include <stdio.h>
#include <stdlib.h>
struct NODE
{
struct NODE *left, *right;;
int data; };
struct NODE * insert(struct NODE *root, int);
struct NODE * delete(struct NODE *root, int);
struct NODE * inorderSuccessor(struct NODE *root);
31
void preorder(struct NODE *);
void inorder(struct NODE *);
void postorder(struct NODE *);
struct NODE * createNode(int);
int main(){
struct NODE *root;
int ch, data;
root = NULL;
while(1){
printf("\n1. Insert\n2. Delete\n3. Display\n4. Exit\nC H
O O S E : ");
scanf("%d", &ch);
switch(ch) {
case 1 :
printf("Enter data to insert : ");
scanf("%d", &data);
root = insert(root, data);
break;
case 2 :
if(root == NULL)
printf("Empty BST...\n");
else{
printf("Enter data to delete : ");
scanf("%d", &data);
root = delete(root, data);
}break;
case 3 :
if(root == NULL)
printf("Empty BST...\n");
else{
printf("\nPreorder : ");
preorder(root);
printf("\nInorder : ");
inorder(root);
printf("\nPostorder : ");
postorder(root);
}
break;
case 4 : exit(0);
default : printf("! INVALID CHOICE !\n");
}
}return 0;
}
struct NODE * insert(struct NODE *root, int data){
if(root == NULL)
return(createNode(data));
if(data == root->data)
32
printf("Duplicate %d not allowed\n", data);
else if(data < root->data)
root->left = insert(root->left, data);
else
root->right = insert(root->right, data);
return root;
}
33
if(root != NULL){
printf("%d\t", root->data);
preorder(root->left);
preorder(root->right);
}
}
void inorder(struct NODE *root){
if(root != NULL){
inorder(root->left);
printf("%d\t", root->data);
inorder(root->right);
}
}
void postorder(struct NODE *root){
if(root != NULL)
{
postorder(root->left);
postorder(root->right);
printf("%d\t", root->data);
}
}
Output :
1. Insert
2. Delete 3. Display
3. Display 4. Exit
4. Exit C H O O S E : 3
C H O O S E : 1
Enter data to insert : 50 Preorder : 50 20 40
70 90
1. Insert Inorder : 20 40 50
2. Delete 70 90
3. Display Postorder : 40 20 90
4. Exit 70 50
C H O O S E : 1 1. Insert
Enter data to insert : 20 2. Delete
3. Display
1. Insert 4. Exit
2. Delete C H O O S E : 2
3. Display Enter data to delete : 50
4. Exit
C H O O S E : 1 1. Insert
Enter data to insert : 70 2. Delete
34
3. Display
1. Insert 4. Exit
2. Delete C H O O S E : 3
3. Display
4. Exit Preorder : 70 20 40
C H O O S E : 1 90
Enter data to insert : 40 Inorder : 20 40 70
1. Insert 90
2. Delete Postorder : 40 20 90
3. Display 70
4. Exit 1. Insert
C H O O S E : 1 2. Delete
Enter data to insert : 90 3. Display
4. Exit
1. Insert C H O O S E : 4
2. Delete
14. Design, develop, and execute a program in C to create a max heap and perform
the following operations :
i)Insertion ii)Deletion iii)Print Largest Value
35
5. Decrement i
6. Exit
delete()
1. If size of array = 0 print “Heap empty” and go to the last step
2. Otherwise Replace the root element with the last leaf node and delete the last
index.
3. Apply heapify(1) on the first index
heapify()
1. Check if the root node is greater than the left and right child.
2. If not, exchange with the child, and apply heapify() on the position where you
exchanged from.
Source Code :
#include <stdio.h>
#include <stdlib.h>
int t_size = 1, u_size = 0;
void displayHeap(int *);
int * insert(int *, int);
void heapify(int *, int);
int main(){
int *heap, data, i, ch, rootIndex, childIndex, temp;
char c;
while(1){
printf("\n1. Create Heap\n2. Insert\n3. Display\n4.
Delete\n5. Print Largest Value\n6. Exit\nC H O O S E : ");
scanf(" %d", &ch);
switch(ch){
case 1 :
do{
printf("Enter data : ");
scanf("%d", &data);
heap = insert(heap, data);
36
heap = (int *) realloc(heap, t_size *
sizeof(int));
printf("Enter data to insert : ");
scanf("%d", &data);
heap[u_size] = data;
childIndex = u_size;
rootIndex = u_size/2;
while(heap[childIndex] > heap[rootIndex] &&
rootIndex > 0){
temp = heap[childIndex];
heap[childIndex] = heap[rootIndex];
heap[rootIndex] = temp;
childIndex /= 2;
rootIndex /= 2;
}
break;
case 3 :
displayHeap(heap);
break;
case 4 :
if(u_size == 0)
printf("Heap empty...\n");
else{
data = heap[1];
heap[1] = heap[u_size];
t_size--; u_size--;
heap = (int *) realloc(heap, t_size *
sizeof(int));
if(heap != NULL)
heapify(heap, 1);
printf("%d deleted...\n", data);
}
break;
case 5 :
if(u_size == 0)
printf("Heap Empty...\n");
else{printf("Largest value : %d\n", heap[1]);}
break;
case 6 : exit(0);
default : printf("! INVALID CHOICE !\n");
} }
return 0;
}
void displayHeap(int *heap){
int i;
printf("INDEX : ");
for(i = 0; i<t_size; i++)
37
printf("%d\t", i);
printf("\nVALUE : ");
for(i = 0; i<t_size; i++)
printf("%d\t", heap[i]);
printf("\n");
}
int * insert(int *heap, int data){
u_size++; t_size++;
if(u_size == 1)
heap = (int *) calloc(t_size, sizeof(int));
else
heap = (int *) realloc(heap, t_size * sizeof(int));
*(heap + u_size) = data;
return heap;
}
void heapify(int *heap, int index){
int lchild, rchild, largestIndex, temp;
lchild = 2*index; rchild = 2*index + 1;
largestIndex = index;
if(lchild <= u_size && heap[lchild] > heap[index])
largestIndex = lchild;
if(rchild <= u_size && heap[rchild] > heap[largestIndex])
largestIndex = rchild;
if(largestIndex != index){
temp = heap[index];
heap[index] = heap[largestIndex];
heap[largestIndex] = temp;
heapify(heap, largestIndex);
}
}
Output :
38
Insert more(y/n) : y 1. Create Heap
Enter data : 100 2. Insert
Insert more(y/n) : y 3. Display
Enter data : 90 4. Delete
Insert more(y/n) : n 5. Print Largest Value
6. Exit
1. Create Heap C H O O S E : 4
2. Insert 100 deleted...
3. Display
4. Delete 1. Create Heap
5. Print Largest Value 2. Insert
6. Exit 3. Display
C H O O S E : 3 4. Delete
INDEX : 0 1 2 5. Print Largest Value
3 4 5 6. Exit
VALUE : 0 100 90 C H O O S E : 5
20 30 50 Largest value : 90
15. Write a program to implement Depth First Search (DFS) graph traversal
methods.
39
1. If the vertex v is not visited print ‘v’.
2. Repeat steps 3 to 4 until all the adjacent vertex are not visited.
3. Explore the adjacent vertices to ‘v’.
4. If adjacent vertex is not visited : push ‘v’ in the stack.Call dfs(graph, adjacent
vertex)
5. If stack is not empty : dfs(pop the stack)
6. Exit
Source Code :
#include <stdio.h>
#include <stdlib.h>
struct NODE{
int data;
struct NODE *next; };
struct NODE *top = NULL;
int *visited;
void push(int);
int pop();
struct NODE * createNode(int);
int searchNode(struct NODE *, int);
void dispAdjList(struct NODE **, int);
void dfs(struct NODE **, int);
int main(){
struct NODE **adjList, *curr;
int n, i, vertex, found;
char ch;
printf("Enter no. of vertices : ");
scanf("%d", &n);
visited = (int *) calloc(n, sizeof(int));
adjList = (struct NODE **) calloc(n, sizeof(struct NODE *));
for(i = 0; i<n; i++)
adjList[i] = NULL;
for(i = 0; i<n; i++){
printf("\nLink node %d (y/n) : ", i);
scanf(" %c", &ch);
while(ch == 'y' || ch == 'Y'){
do{
printf("Node no.(0-%d) : ", n-1);
scanf("%d", &vertex);
} while (vertex < 0 || vertex >= n);
if(adjList[i] == NULL)
adjList[i] = createNode(vertex);
else{
found = searchNode(adjList[i], vertex);
if(!found){
40
curr = adjList[i];
while(curr->next != NULL)
curr = curr->next;
curr->next = createNode(vertex);
}
else
printf("Already linked...\n");
}
printf("Link More(y/n) : ");
scanf(" %c", &ch);
}}
printf("\nDisplaying adjList\n");
dispAdjList(adjList, n);
do{
for(i = 0; i<n; i++)
visited[i] = 0;
printf("Choose starting vertex for DFS : ");
scanf("%d", &vertex);
dfs(adjList, vertex);
printf("\nTraverse it again(y/n) : ");
scanf(" %c", &ch);
} while (ch == 'y' || ch == 'Y');
return 0;
}
struct NODE * createNode(int data){
struct NODE *newNode;
newNode = (struct NODE *) malloc(sizeof(struct NODE));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void dispAdjList(struct NODE **adjList, int n){
int i;
struct NODE *curr;
for(i = 0; i<n; i++){
printf("%d : ", i);
curr = adjList[i];
while(curr != NULL){
printf("%d => ", curr->data);
curr = curr->next;
} printf(" N");
printf("\n");
}
}
int searchNode(struct NODE * node, int data){
if(node == NULL)
return 0;
41
else{
while(node != NULL){
if(node->data == data)
return 1;
node = node->next;
}
return 0;
}
}
void push(int n){
struct NODE * temp;
temp = createNode(n);
temp->next = top;
top = temp;
}
int pop(){
int data = -1;
if(top != NULL){
data = top->data;
top = top->next;
}
return data;
}
void dfs(struct NODE **adjList, int v){
struct NODE *vertex;
int n;
if(visited[v] == 0){
printf("%d => ", v);
visited[v] = 1;
}
vertex = adjList[v];
while(vertex != NULL){
n = vertex->data;
if(visited[n] == 0){
push(v);
dfs(adjList, n);
}
vertex = vertex->next;
}
v = pop();
if(v != -1)
dfs(adjList, v);
}
Output :
Enter no. of vertices : 4
42
Node no.(0-3) : 3
Link More(y/n) : n
Displaying adjList
0 : 3 => N
1 : 3 => N
2 : 3 => N
3 : 0 => 1 => 2 => N
Choose starting vertex for DFS : 3
3 => 0 => 1 => 2 =>
Traverse it again(y/n) : n
16. Write a program to implement Depth First Search (BFS) graph traversal
methods.
43
2. Repeat the steps 3 to 4 until all the adjacent vertices are not visited.
3. Explore the adjacent vertices to ‘v’.
4. If adjacent vertex is not visited : push ‘adjacent vertex’ to queue.
5. If queue is not empty apply bfs(dequeue())
6. Exit
Source Code :
#include <stdio.h>
#include <stdlib.h>
struct NODE{
int data;
struct NODE *next;
};
struct NODE *front = NULL, *rear = NULL;
int n, *visited;
void enqueue(int);
int dequeue();
struct NODE * createNode(int);
int searchNode(struct NODE *, int);
void insertNode(struct NODE *, int);
void bfs(struct NODE **, int);
int main(){
struct NODE **adjList, *curr;
int i, vertex, v;
char ch;
printf("Enter no. of vertices : ");
scanf("%d", &n);
adjList = (struct NODE **) calloc(n, sizeof(struct NODE *));
for(i = 0; i<n; i++)
adjList[i] = NULL;
visited = (int *) calloc(n, sizeof(int));
for(vertex = 0; vertex < n; vertex++){
printf("Want to link %d (y/n) : ", vertex);
scanf(" %c", &ch);
while(ch == 'y' || ch == 'Y'){
do{ printf("Link with(0 - %d) : ", n-1);
scanf("%d", &v);
} while (v < 0 || v >= n);
if(adjList[vertex] == NULL)
adjList[vertex] = createNode(v);
else{
if(searchNode(adjList[vertex], v) == -1)
insertNode(adjList[vertex], v);
else
printf("Duplicate(%d) not allowed...\n", v);
}
printf("Link More(y/n) : ");
44
scanf(" %c", &ch);
}
}
for(i = 0; i<n; i++){
printf("%d : ", i);
curr = adjList[i];
while(curr != NULL){
printf("%d -> ", curr->data);
curr = curr->next;
}
printf("N\n");
}
do{
for(i = 0; i<n; i++)
visited[i] = 0;
printf("Enter a vertex to start BFS : ");
scanf("%d", &v);
bfs(adjList, v);
printf("N");
printf("\nPerform BFS again(y/n) : ");
scanf(" %c", &ch);
} while (ch == 'y' || ch == 'Y');
return 0;
}
void enqueue(int data){
struct NODE * newNode;
newNode = createNode(data);
if(front == NULL)
front = rear = newNode;
else{
rear->next = newNode;
rear = newNode;
}
}
int dequeue(){
int data;
if(front == NULL)
return -1;
data = front->data;
if(front == rear)
front = rear = NULL;
else
front = front->next;
return data;
}
struct NODE * createNode(int data){
struct NODE * temp;
45
temp = (struct NODE *) malloc(sizeof(struct NODE));
temp->data = data;
temp->next = NULL;
return temp;
}
int searchNode(struct NODE * node, int data){
while(node != NULL){
if(node->data == data)
return 1;
node = node->next;
}
return -1;
}
void insertNode(struct NODE * node, int data){
while(node->next != NULL)
node = node->next;
node->next = createNode(data);
}
void bfs(struct NODE **adjList, int v){
struct NODE *curr;
if(visited[v] == 0){
visited[v] = 1;
printf("%d -> ", v);
}
curr = adjList[v];
while(curr != NULL){
if(visited[curr->data] == 0){
printf("%d -> ", curr->data);
visited[curr->data] = 1;
enqueue(curr->data);
}
curr = curr->next;
}
v = dequeue();
if(v != -1)
bfs(adjList, v);
}
Output :
Enter no. of vertices : 4
Want to link 0 (y/n) : y
Link with(0 - 3) : 3
Link More(y/n) : n
Want to link 1 (y/n) : y
Link with(0 - 3) : 3
Link More(y/n) : n
Want to link 2 (y/n) : y
46
Link with(0 - 3) : 3
Link More(y/n) : n
Want to link 3 (y/n) : y
Link with(0 - 3) : 0
Link More(y/n) : y
Link with(0 - 3) : 1
Link More(y/n) : y
Link with(0 - 3) : 2
Link More(y/n) : n
0 : 3 -> N
1 : 3 -> N
2 : 3 -> N
3 : 0 -> 1 -> 2 -> N
Enter a vertex to start BFS : 0
0 -> 3 -> 1 -> 2 -> N
Perform BFS again(y/n) : n
17. Create a text file containing the name, height, weight of the students in a class.
Perform Quick sort and Merge sort on this data and store the resultant data in two
separate files. Also write the time taken by the two sorting methods into the
respective files.
Sony Mathew 5.5 60 Arun Sajeev 5.7 58 Rajesh Kumar 6.1 70
Objective:
To understand data files and file handling in C. Helps to understand sorting in
files.
Algorithm:
1. Files :
2. Open file1.txt and file2.txt with “a+”(append and read) option, so that the
previous content of the file is not deleted. If files don’t exist, they will be
created.
3. Explicitly write a newline (“\n”) to the destination file to enhance readability.
4. Write content from source file to destination file.
5. Display the contents in file2.txt to console (stdout).
Quick sort :
1. Pick an element, called a pivot, from the array.
2. Partition the array into two halves, the left side of the array containing
3. Elements less than the pivot element, and the right side of the array containing
47
elements greater than the pivot element.
4. Recursively sort the left side of the array and the right side of the array.
5. Return the array.
Merge sort :
1: Start
2: Declare an array and left, right, mid variable
3: Perform merge function.
mergesort(array,left,right)
mergesort (array, left, right)
if left > right
return
else
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
4: Stop
Source Code :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int partition(int, int);
void quickSort(int, int);
struct stud{
char name[20];
float hgt, wgt;
}s[10];
struct Name{
char st_name[10];
}
name[10], copy[10];
void quickSort(int low, int high){
int pIndex;
if (low<high){
pIndex = partition(low, high);
quickSort(low, pIndex-1);
quickSort(pIndex+1, high);
}
48
}
int partition(int low, int high){
char pivot[10], temp[10];
int i, j;
strcpy(pivot, name[low].st_name);
i = low; j = high;
while(i<j){
while(strcmp(name[i].st_name, pivot) == 0 ||
strcmp(name[i].st_name, pivot) == -1)
i++;
while(strcmp(name[j].st_name, pivot) == 1)
j--;
if(i<j){
strcpy(temp, name[i].st_name);
strcpy(name[i].st_name, name[j].st_name);
strcpy(name[j].st_name, temp);
}
}
strcpy(temp, name[j].st_name);
strcpy(name[j].st_name, name[low].st_name);
strcpy(name[low].st_name, temp);
return j;
}
void merge(int l, int m, int r){
int i, j, k;
int n1 = m - l + 1, n2 = r - m;
struct Name L[10], R[10];
for (i = 0; i < n1; i++)
strcpy(L[i].st_name,name[l + i].st_name);
for (j = 0; j < n2; j++)
strcpy(R[j].st_name, name[m + 1 + j].st_name);
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2) {
if (strcmp(L[i].st_name,R[j].st_name) == -1) {
strcpy(name[k].st_name, L[i].st_name);
i++;
}
else {
strcpy(name[k].st_name, R[j].st_name);
49
j++;
}
k++;
}
while (i < n1) {
strcpy(name[k].st_name, L[i].st_name);
i++;
k++;
}
while (j < n2) {
strcpy(name[k].st_name, R[j].st_name);
j++;
k++;
}
}
void mergeSort(int l, int r){
int m;
if (l < r) {
m = l + (r - l) / 2;
mergeSort(l, m); mergeSort(m + 1, r); merge(l, m, r);
}
}
int main(){
FILE *fp;
int i,n, k;
char c, str[100];
fp = fopen("student.txt", "w");
printf("Enter record of student:\n\n");
printf("Enter no. of entries : ");
scanf("%d", &n);
for(i = 0; i<n; i++){
printf("\nEnter name of %d th student: ",i+1);
scanf(" %s", s[i].name);
fprintf(fp, "%s ",s[i].name);
}
fprintf(fp, "\n");
for(i = 0; i<n; i++){
printf("\nEnter height of %d th student: ",i+1);
scanf(" %f", &s[i].hgt);
fprintf(fp, "%f ",s[i].hgt);
50
}
fprintf(fp, "\n");
for(i = 0; i<n; i++){
printf("\nEnter weight of %d th student: ",i+1);
scanf(" %f", &s[i].wgt);
fprintf(fp, "%f ",s[i].wgt);
}
printf("\nRecord stored in file...\n");
fclose(fp);
fp = fopen("student.txt", "r");
i = 0; k = 0;
while((c = getc(fp)) != '\n'){
if (c == ' '){
str[i] = '\0';
strcpy(name[k].st_name, str);
i = 0;
k++;
}
else{
str[i] = c; i++;
}
}
fclose(fp);
fp = fopen("student.txt", "r");
while((c = getc(fp)) != EOF)
printf("%c", c);
fclose(fp);
quickSort(0, n-1);
printf("\n");
for(i = 0; i<n; i++)
printf("%s\t", name[i].st_name);
fp = fopen("quickSortFile.txt", "w");
for(i = 0; i<n; i++)
fprintf(fp, "%s\t", name[i].st_name);
fclose(fp);
printf("\n…Quicksort writing is done\n");
51
fp = fopen("student.txt", "r");
i = 0;
k = 0;
while((c = getc(fp)) != '\n'){
if (c == ' '){
str[i] = '\0';
strcpy(name[k].st_name, str);
i = 0;
k++;
}
else{
str[i] = c;
i++;
}
}
fclose(fp);
mergeSort(0,n- 1);
printf("\n");
for(i = 0; i<n; i++)
printf("%s\t", name[i].st_name);
fp = fopen("mergedSortFile.txt", "w");
for(i = 0; i<n; i++)
fprintf(fp, "%s\t", name[i].st_name);
fclose(fp);
printf("\n…Mergesort writing is done\n");
return 0;
}
Output :
Enter record of student:
Enter no. of entries : 3
Enter name of 1 th student: mohan
Enter name of 2 th student: radhika
Enter name of 3 th student: keshava
Enter height of 1 th student: 151.23
Enter height of 2 th student: 155
Enter height of 3 th student: 160.15
Enter weight of 1 th student: 50
Enter weight of 2 th student: 45
Enter weight of 3 th student: 55
52
Record stored in file...
mohan radhika keshava
151.229996 155.000000 160.149994
50.000000 45.000000 55.000000
keshava mohan radhika …Quicksort writing is done
keshava mohan radhika …Mergesort writing is done
18. Write a program to sort a set of numbers using Heap sort and find a particular
number from the sorted set using Binary Search.
53
1. Check if the root node is greater than the left and right child.
2. If not, exchange with the child, and apply heapify() on the position where you
exchanged from.
HeapSort()
1. Declare an array ‘sortedArray’.
2. Continuously apply delete() on the heap and store the deleted element in the
‘sortedArray’, till the heap becomes empty.
BinarySearch(data, low, high)
1. Repeat steps 2 to 5 till low<=high
2. Assign mid = (low+high) /2
3. If data < arr[mid] : low = mid+1
4. Otherwise if data > arr[mid] : high = mid-1
5. Otherwise print ‘data found at the respective position’ and return
6. Print ‘data not found’
7. Exit
Source Code :
#include <stdio.h>
#include <stdlib.h>
int t_size = 1, u_size = 0;
int array_size;
void displayHeap(int *);
int * insert(int *, int);
void heapify(int *, int);
void binarySearch(int *, int);
int main(){
int *heap, *sortedArray, i, ch, rootIndex, childIndex, temp,
data;
char c;
while(1){
printf("\n1. Create Heap\n2. Display\n3. Heap Sort\n4.
Binary Search\n5. Exit\nC H O O S E : ");
scanf(" %d", &ch);
switch(ch){
case 1 :
do{
printf("Enter data : ");
scanf("%d", &data);
heap = insert(heap, data);
54
heapify(heap, i);
break;
case 2 :
displayHeap(heap);
break;
case 3 :
if(u_size == 0)
printf("Heap empty...\n");
else{
sortedArray = (int *) calloc(u_size,
sizeof(int));
array_size = u_size;
for(i = 0; i<array_size; i++){
sortedArray[i] = heap[1];
heap[1] = heap[u_size];
t_size--; u_size--;
heap = (int *) realloc(heap, t_size *
sizeof(int));
if(heap != NULL)
heapify(heap, 1);
}
}
printf("\nSorted Array : ");
for(i = 0; i<array_size; i++)
printf("%d\t", sortedArray[i]);
break;
case 4 :
if(heap == NULL)
printf("Empty Heap...\n");
else{
do{
printf("Size of the array : %d\n",
array_size);
printf("Enter the data to search : ");
scanf("%d", &data);
binarySearch(sortedArray, data);
printf("Want to search again(y/n) : ");
scanf(" %c", &ch);
} while (ch == 'y' || ch == 'Y');
}
case 5 : exit(0);
default : printf("! INVALID CHOICE !\n"); }
}
return 0;
}
void displayHeap(int *heap){
int i;
55
printf("INDEX : ");
for(i = 0; i<t_size; i++)
printf("%d\t", i);
printf("\nVALUE : ");
for(i = 0; i<t_size; i++)
printf("%d\t", heap[i]);
printf("\n");
}
int * insert(int *heap, int data){
u_size++; t_size++;
if(u_size == 1)
heap = (int *) calloc(t_size, sizeof(int));
else
heap = (int *) realloc(heap, t_size * sizeof(int));
*(heap + u_size) = data;
return heap;
}
void heapify(int *heap, int index){
int lchild, rchild, largestIndex, temp;
lchild = 2*index; rchild = 2*index + 1;
largestIndex = index;
if(lchild <= u_size && heap[lchild] > heap[index])
largestIndex = lchild;
if(rchild <= u_size && heap[rchild] > heap[largestIndex])
largestIndex = rchild;
if(largestIndex != index){
temp = heap[index];
heap[index] = heap[largestIndex];
heap[largestIndex] = temp;
heapify(heap, largestIndex); }
}
void binarySearch(int *arr, int elem){
int low, high, mid;
low = 0; high = array_size-1;
while(low <= high){
mid = (low+high)/2;
if(elem < arr[mid])
low = mid+1;
else if(elem > arr[mid])
high = mid - 1;
else{
printf("Element %d found at position %d.\n", elem,
mid+1);
break;
}}
if(low > high)
56
printf("Element %d not found...\n", elem);
}
Output :
1. Create Heap
2. Display 1. Create Heap
3. Heap Sort 2. Display
4. Binary Search 3. Heap Sort
5. Exit 4. Binary Search
C H O O S E : 1 5. Exit
Enter data : 50 C H O O S E : 3
Insert more(y/n) : y
Enter data : 20 Sorted Array : 200 100
Insert more(y/n) : y 90 50 20
Enter data : 100 1. Create Heap
Insert more(y/n) : y 2. Display
Enter data : 90 3. Heap Sort
Insert more(y/n) : y 4. Binary Search
Enter data : 200 5. Exit
Insert more(y/n) : n C H O O S E : 4
Size of the array : 5
1. Create Heap Enter the data to search : 90
2. Display Element 90 found at position 3.
3. Heap Sort Want to search again(y/n) : n
4. Binary Search
5. Exit
C H O O S E : 2
INDEX : 0 1 2
3 4 5
VALUE : 0 200 90
100 50 20
19. Implement a Hash table using Chaining method. Let the size of hash table be 10
so that the index varies from 0 to 9.
Algorithm:
57
1.
Declare a structure NODE with fields int ‘data’, struct NODE * left, *right.
2.
Declare ‘hashTable’ as an array of pointers to struct NODE.
3.
Read the elements.
4.
Hash the element to the respective position in the hashtable using function hash(x)
= x%10.
5. Read the ‘elem’ to be searched. Generate the key and search the element in the
hashtable.
6. Read the ‘elem’ to be dropped. Generate the key and delete the element in the
hashtable.
Source Code :
#include <stdio.h>
#include <stdlib.h>
#define HASH(x) x%n
struct NODE {
int data;
struct NODE *next;
};
int main(){
struct NODE **hashTable, *temp, *curr, *prev;
int ch, n, i, num, key, elemCnt;
printf("Size of the HashTable : ");
scanf("%d", &n);
hashTable = (struct NODE **) calloc(n, sizeof(struct NODE
*));
for(i = 0; i<n; i++)
*(hashTable + i) = NULL;
elemCnt = 0;
while(1)
{
printf("\nHASH TABLE MENU \n");
printf("1. Insert\n2. Remove\n3. Display\n4.
DisplaySize\n5. Exit\nC H O O S E : ");
scanf("%d", &ch);
switch(ch){
case 1 :
printf("Enter data : ");
scanf("%d", &num);
temp = (struct NODE *) calloc(1, sizeof(struct
NODE));
temp->data = num;
temp->next = NULL;
key = HASH(num);
if(*(hashTable + key) == NULL)
*(hashTable + key) = temp;
58
else{
curr = *(hashTable + key);
while(curr->next != NULL)
curr = curr->next;
curr->next = temp;
}
printf("%d successfully hashed...\n", num);
elemCnt++;
break;
case 2 :
printf("Element to remove : ");
scanf("%d", &num);
key = HASH(num);
curr = *(hashTable + key);
while(curr != NULL){
if(curr->data == num){
temp = curr;
if(curr == *(hashTable + key))
*(hashTable + key) = curr->next;
else
prev->next = curr->next;
free(curr);
printf("%d removed ...\n", num);
break;
}
prev = curr;
curr = curr->next;
}
if(curr == NULL)
printf("! Value not found !\n");
break;
case 3 :
for(i = 0; i<n; i++){
printf("%d : ", i);
curr = *(hashTable + i);
while(curr != NULL){
printf("%d -> ", curr->data);
curr = curr->next;
}
printf("N\n");
}
break;
case 4 : printf("Element Count : %d\n", elemCnt);
break;
case 5 : exit(0);
default : printf("\n! INVALID CHOICE !");
59
} }
return 0;
}
Output :
60
3. Display C H O O S E : 3
4. DisplaySize 0 : 20 -> N
5. Exit 1 : N
C H O O S E : 1 2 : N
Enter data : 45 3 : N
45 successfully hashed... 4 : N
5 : 5 -> 45 -> N
HASH TABLE MENU 6 : N
1. Insert 7 : N
2. Remove 8 : 8 -> N
3. Display 9 : N
4. DisplaySize
5. Exit HASH TABLE MENU
C H O O S E : 1 1. Insert
Enter data : 8 2. Remove
8 successfully hashed... 3. Display
4. DisplaySize
5. Exit
C H O O S E : 5
20. Implement a Hash table that uses Linear Probing for collision resolution.
61
where not a single data has been entered (means data does not exist in the hash
table).
9. Exit
Source Code :
#include <stdio.h>
#include <stdlib.h>
struct item{
int key;
int value;
};
struct hashtable_item{
int flag;
struct item *data;
};
struct hashtable_item *array;
int size = 0;
int max = 10;
void init_array(){
int i;
for (i = 0; i < max; i++){
array[i].flag = 0;
array[i].data = NULL;
}
}
int hashcode(int key){
return (key % max);
}
void insert(int key, int value){
int index = hashcode(key);
int i = index;
struct item *new_item = (struct item *)malloc(sizeof(struct
item));
new_item->key = key;
new_item->value = value;
while (array[i].flag == 1){
if (array[i].data->key == key){
printf("\n Key already exists, hence updating its
value \n");
array[i].data->value = value;
return;
}
62
i = (i + 1) % max;
if (i == index){
printf("\n Hash table is full, cannot insert any
more item \n");
return;
}
}
array[i].flag = 1;
array[i].data = new_item;
size++;
printf("\n Key (%d) has been inserted \n", key);
}
void remove_element(int key){
int index = hashcode(key);
int i = index;
while (array[i].flag != 0){
if (array[i].flag == 1 && array[i].data->key == key){
array[i].flag = 2;
array[i].data = NULL;
size--;
printf("\n Key (%d) has been removed \n", key);
return;
}
i = (i + 1) % max;
if (i == index)
{
break;
}
}
printf("\n This key does not exist \n");
}
void display(){
int i;
for (i = 0; i < max; i++){
struct item *current = (struct item *)array[i].data;
if (current == NULL){
printf("\n Array[%d] has no elements \n", i);
}
else{
printf("\n Array[%d] has elements -: \n %d (key) and
%d(value) ", i, current->key, current->value);
63
}
}
}
int size_of_hashtable(){return size;}
int main(){
int choice, key, value, n, c;
array = (struct hashtable_item *)malloc(max * sizeof(struct
hashtable_item));
init_array();
do{
printf("Implementation of Hash Table in C with Linear
Probing \n\n");
printf("MENU-: \n1.Inserting item in the Hashtable"
"\n2.Removing item from the Hashtable"
"\n3.Check the size of Hashtable"
"\n4.Display Hashtable"
"\n\n Please enter your choice-:");
scanf("%d", &choice);
switch (choice){
case 1:
printf("Inserting element in Hashtable\n");
printf("Enter key and value-:\t");
scanf("%d %d", &key, &value);
insert(key, value);
break;
case 2:
printf("Deleting in Hashtable \n Enter the key to
delete-:");
scanf("%d", &key);
remove_element(key);
break;
case 3:
n = size_of_hashtable();
printf("Size of Hashtable is-:%d\n", n);
break;
case 4:
display();
break;
default:
printf("Wrong Input\n");
}
64
printf("\n Do you want to continue-:(press 1 for
yes)\t");
scanf("%d", &c);
} while (c == 1);
return 0;
}
Output :
65
Do you want to continue- 1.Inserting item in the
:(press 1 for yes) 1 Hashtable
Implementation of Hash Table in 2.Removing item from the
C with Linear Probing Hashtable
3.Check the size of Hashtable
MENU-: 4.Display Hashtable
1.Inserting item in the
Hashtable Please enter your choice-:2
2.Removing item from the Deleting in Hashtable
Hashtable Enter the key to delete-:29
3.Check the size of Hashtable
4.Display Hashtable Key (29) has been removed
66