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

BCA data structure lab file

The document outlines a Data Structures Lab course at Bhawan Institute of Technology for the academic year 2024-25, detailing various C programming tasks related to data structures. It includes exercises on arrays, matrices, stacks, linked lists, binary search trees, and sorting algorithms. Each task is designed to enhance students' understanding of fundamental data structures and their implementations in C.

Uploaded by

onlymusic2332
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

BCA data structure lab file

The document outlines a Data Structures Lab course at Bhawan Institute of Technology for the academic year 2024-25, detailing various C programming tasks related to data structures. It includes exercises on arrays, matrices, stacks, linked lists, binary search trees, and sorting algorithms. Each task is designed to enhance students' understanding of fundamental data structures and their implementations in C.

Uploaded by

onlymusic2332
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

BHAGWANT INSTITUTE OF TECHNOLOGY

17th Milestone Bijnor- Delhi highway, Distt- Muzaffarnagar

Data Structures Lab (BCS351)– ODD Sem


2024-25
Department : CSE & CA
Lecture Topic
No.
1 Write a C program to find the sum of all elements in an
array

2
Write a C program to find the largest element in an array

3 Write a C program to find the smallest element in an array

4 Write a C program to find the second largest element in an


array

5 Write a C program to find the duplicate elements in an


array

6 Write a C program to multiply two matrices entered by the


user

7 Write a C program to check if a matrix is symmetric or not

8 Write a C program to find the sum of each row and each


column of a matrix

9 Write a C program to check whether the given matrix is


sparse matrix or not
10 C program to implement stack using arrays
11 C program to implement evaluation of postfix notation
12 C program to implement conversion of infix to postfix
13 C Program to Perform Singly Linked List Operations
14
C Program to Implement Circular Doubly Linked List
15 C Program to Find the Largest Element in a Doubly Linked
List
16 C program to remove element from linked list
17 c programs polyniomial addition on linked list
18 C program to implement linear probe for collision
19 C program to implement subtraction hashing
20 C program to implement to create binary search tree
21 C program to implement preorder,postorder,inorder
22 C program to search largest node
23 C program to implement smallest node
24 C program to count number of nodes
25 C program to implement min heap
26 C program to implement max heap
27 C program to implement heapsort
28 C program to implement expression tree
29 C program to represent a graph using adjacency matrix
30 C program to implement bubble sort
31- C program to implement insertion sort
32 C program to implement quick sort
33 C program to implement merge sort
34 C program to implement selection sort
35 C program to implement Radix sort
32 C program to implement linear search
33 C program to implement binary search
34 C program to implement modulo division
35 C program to implement fold shift
32 C program to implement linear probe for collision
33 C program to implement subtraction hashing
1)Write a C program to find the sum of all elements in an array
2)Write a C program to find the largest element in an array
3)Write a C program to find the smallest element in an array
4)Write a C program to find the second largest element in an array
5)Write a C program to find the duplicate elements in an array
6)Write a C program to multiply two matrices entered by the user
Write a C program to check if a matrix is symmetric or not

7) Write a C program to find the sum of each row and each column of a
matrix
8) Write a C program to check whether the given matrix is sparse matrix or
not

(program 1-8 Do it Yourself)

9) C program to implement stack using arrays


Solution:
#include<stdio.h>

int stack[100],choice,n,top,x,i;

void push(void);

void pop(void);

void display(void);

int main()

{
top=-1;

printf("\n Enter the size of STACK[MAX=100]:");-

scanf("%d",&n);

printf("\n\t STACK OPERATIONS USING ARRAY");

printf("\n\t--------------------------------");

printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");

do

printf("\n Enter the Choice:");

scanf("%d",&choice);

switch(choice)

case 1:

push();

break;-

case 2:

pop();

break;

}
case 3:

display();

break;

case 4:

printf("\n\t EXIT POINT ");

break;

default:

printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");

while(choice!=4);

return 0;

void push()

{
if(top>=n-1)

printf("\n\tSTACK is over flow");

else

printf(" Enter a value to be pushed:");

scanf("%d",&x);

top++;

stack[top]=x;

void pop()

if(top<=-1)

printf("\n\t Stack is under flow");

else

printf("\n\t The popped elements is %d",stack[top]);


top--;

void display()

if(top>=0)

printf("\n The elements in STACK \n");

for(i=top; i>=0; i--)

printf("\n%d",stack[i]);

printf("\n Press Next Choice");

else

printf("\n The STACK is empty");

10) C program to implement evaluation of postfix notation

1. Solution: #include <stdio.h>


2. #include <stdlib.h>
3. #define MAX_SIZE 100
4. // Stack implementation
5. int stack[MAX_SIZE];
6. int top = -1;
7. void push(int item) {
8. if (top >= MAX_SIZE - 1) {
9. printf("Stack Overflow\n");
10. return;
11. }
12. top++;
13. stack[top] = item;
14. }
15. int pop() {
16. if (top < 0) {
17. printf("Stack Underflow\n");
18. return -1;
19. }
20. int item = stack[top];
21. top--;
22. return item;
23. }
24. int is_operator(char symbol) {
25. if (symbol == '+' || symbol == '-' || symbol == '*' || symbol == '/') {
26. return 1;
27. }
28. return 0;
29. }
30. int evaluate(char* expression) {
31. int i = 0;
32. char symbol = expression[i];
33. int operand1, operand2, result;
34.
35. while (symbol != '\0') {
36. if (symbol >= '0' && symbol <= '9') {
37. int num = symbol - '0';
38. push(num);
39. }
40. else if (is_operator(symbol)) {
41. operand2 = pop();
42. operand1 = pop();
43. switch(symbol) {
44. case '+': result = operand1 + operand2; break;
45. case '-': result = operand1 - operand2; break;
46. case '*': result = operand1 * operand2; break;
47. case '/': result = operand1 / operand2; break;
48. }
49. push(result);
50. }
51. i++;
52. symbol = expression[i];
53. }
54. result = pop();
55. return result;
56. }
57.
58. int main() {
59. char expression[] = "5 6 7 + * 8 -";
60. int result = evaluate(expression);
61. printf("Result= %d\n", result);
62. return 0;
63. }

11) C program to implement conversion of infix to postfix


Solution:
1. #include <limits.h>
2. #include <stdio.h>
3. #include <stdlib.h>
4. #define MAX 20
5.
6. char stk[20];
7. int top = -1;
8.
9. int isEmpty()
10. {
11. return top == -1;
12. }
13. int isFull()
14. {
15. return top == MAX - 1;
16. }
17.
18. char peek()
19. {
20. return stk[top];
21. }
22.
23. char pop()
24. {
25. if(isEmpty())
26. return -1;
27.
28. char ch = stk[top];
29. top--;
30. return(ch);
31. }
32.
33. void push(char oper)
34. {
35. if(isFull())
36. printf("Stack Full!!!!");
37.
38. else{
39. top++;
40. stk[top] = oper;
41. }
42. }
43.
44. int checkIfOperand(char ch)
45. {
46. return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
47. }
48.
49. int precedence(char ch)
50. {
51. switch (ch)
52. {
53. case '+':
54. case '-':
55. return 1;
56.
57. case '*':
58. case '/':
59. return 2;
60.
61. case '^':
62. return 3;
63. }
64. return -1;
65. }
66.
67. int covertInfixToPostfix(char* expression)
68. {
69. int i, j;
70.
71. for (i = 0, j = -1; expression[i]; ++i)
72. {
73. if (checkIfOperand(expression[i]))
74. expression[++j] = expression[i];
75.
76. else if (expression[i] == '(')
77. push(expression[i]);
78.
79. else if (expression[i] == ')')
80. {
81. while (!isEmpty() && peek() != '(')
82. expression[++j] = pop();
83. if (!isEmpty() && peek() != '(')
84. return -1;
85. else
86. pop();
87. }
88. else
89. {
90. while (!isEmpty() && precedence(expression[i]) <= precedence(p
eek()))
91. expression[++j] = pop();
92. push(expression[i]);
93. }
94.
95. }
96.
97. while (!isEmpty())
98. expression[++j] = pop();
99.
100. expression[++j] = '\0';
101. printf( "%s", expression);
102. }
103.
104. int main()
105. {
106. char expression[] = "((x+(y*z))-w)";
107. covertInfixToPostfix(expression);
108. return 0;
109. }

12)C Program to Perform Singly Linked List Operations

Solution:
#include <stdio.h>
#include <stdlib.h>

// Linked List Node


struct node {
int info;
struct node* link;
};
struct node* start = NULL;

// Function to create list with n nodes initially


void createList()
{
if (start == NULL) {
int n;
printf("\nEnter the number of nodes: ");
scanf("%d", &n);
if (n != 0) {
int data;
struct node* newnode;
struct node* temp;
newnode = malloc(sizeof(struct node));
start = newnode;
temp = start;
printf("\nEnter number to"
" be inserted : ");
scanf("%d", &data);
start->info = data;

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


newnode = malloc(sizeof(struct node));
temp->link = newnode;
printf("\nEnter number to"
" be inserted : ");
scanf("%d", &data);
newnode->info = data;
temp = temp->link;
}
}
printf("\nThe list is created\n");
}
else
printf("\nThe list is already created\n");
}

// Function to traverse the linked list


void traverse()
{
struct node* temp;

// List is empty
if (start == NULL)
printf("\nList is empty\n");

// Else print the LL


else {
temp = start;
while (temp != NULL) {
printf("Data = %d\n", temp->info);
temp = temp->link;
}
}
}

// Function to insert at the front


// of the linked list
void insertAtFront()
{
int data;
struct node* temp;
temp = malloc(sizeof(struct node));
printf("\nEnter number to"
" be inserted : ");
scanf("%d", &data);
temp->info = data;

// Pointer of temp will be


// assigned to start
temp->link = start;
start = temp;
}

// Function to insert at the end of


// the linked list
void insertAtEnd()
{
int data;
struct node *temp, *head;
temp = malloc(sizeof(struct node));

// Enter the number


printf("\nEnter number to"
" be inserted : ");
scanf("%d", &data);

// Changes links
temp->link = 0;
temp->info = data;
head = start;
while (head->link != NULL) {
head = head->link;
}
head->link = temp;
}

// Function to insert at any specified


// position in the linked list
void insertAtPosition()
{
struct node *temp, *newnode;
int pos, data, i = 1;
newnode = malloc(sizeof(struct node));

// Enter the position and data


printf("\nEnter position and data :");
scanf("%d %d", &pos, &data);

// Change Links
temp = start;
newnode->info = data;
newnode->link = 0;
while (i < pos - 1) {
temp = temp->link;
i++;
}
newnode->link = temp->link;
temp->link = newnode;
}

// Function to delete from the front


// of the linked list
void deleteFirst()
{
struct node* temp;
if (start == NULL)
printf("\nList is empty\n");
else {
temp = start;
start = start->link;
free(temp);
}
}

// Function to delete from the end


// of the linked list
void deleteEnd()
{
struct node *temp, *prevnode;
if (start == NULL)
printf("\nList is Empty\n");
else {
temp = start;
while (temp->link != 0) {
prevnode = temp;
temp = temp->link;
}
free(temp);
prevnode->link = 0;
}
}

// Function to delete from any specified


// position from the linked list
void deletePosition()
{
struct node *temp, *position;
int i = 1, pos;

// If LL is empty
if (start == NULL)
printf("\nList is empty\n");

// Otherwise
else {
printf("\nEnter index : ");

// Position to be deleted
scanf("%d", &pos);
position = malloc(sizeof(struct node));
temp = start;

// Traverse till position


while (i < pos - 1) {
temp = temp->link;
i++;
}

// Change Links
position = temp->link;
temp->link = position->link;

// Free memory
free(position);
}
}

// Function to find the maximum element


// in the linked list
void maximum()
{
int a[10];
int i;
struct node* temp;

// If LL is empty
if (start == NULL)
printf("\nList is empty\n");

// Otherwise
else {
temp = start;
int max = temp->info;

// Traverse LL and update the


// maximum element
while (temp != NULL) {

// Update the maximum


// element
if (max < temp->info)
max = temp->info;
temp = temp->link;
}
printf("\nMaximum number "
"is : %d ",
max);
}
}

// Function to find the mean of the


// elements in the linked list
void mean()
{
int a[10];
int i;
struct node* temp;

// If LL is empty
if (start == NULL)
printf("\nList is empty\n");

// Otherwise
else {
temp = start;

// Stores the sum and count of


// element in the LL
int sum = 0, count = 0;
float m;

// Traverse the LL
while (temp != NULL) {

// Update the sum


sum = sum + temp->info;
temp = temp->link;
count++;
}

// Find the mean


m = sum / count;

// Print the mean value


printf("\nMean is %f ", m);
}
}

// Function to sort the linked list


// in ascending order
void sort()
{
struct node* current = start;
struct node* index = NULL;
int temp;

// If LL is empty
if (start == NULL) {
return;
}

// Else
else {

// Traverse the LL
while (current != NULL) {
index = current->link;

// Traverse the LL nestedly


// and find the minimum
// element
while (index != NULL) {

// Swap with it the value


// at current
if (current->info > index->info) {
temp = current->info;
current->info = index->info;
index->info = temp;
}
index = index->link;
}

// Update the current


current = current->link;
}
}
}
// Function to reverse the linked list
void reverseLL()
{
struct node *t1, *t2, *temp;
t1 = t2 = NULL;

// If LL is empty
if (start == NULL)
printf("List is empty\n");

// Else
else {

// Traverse the LL
while (start != NULL) {

// reversing of points
t2 = start->link;
start->link = t1;
t1 = start;
start = t2;
}
start = t1;

// New head Node


temp = start;

printf("Reversed linked "


"list is : ");

// Print the LL
while (temp != NULL) {
printf("%d ", temp->info);
temp = temp->link;
}
}
}
// Function to search an element in linked list
void search()
{
int found = -1;
// creating node to traverse
struct node* tr = start;

// first checking if the list is empty or not


if (start == NULL) {
printf("Linked list is empty\n");
}
else {
printf("\nEnter the element you want to search: ");
int key;
scanf("%d", &key);

// checking by traversing
while (tr != NULL) {
// checking for key
if (tr->info == key) {
found = 1;
break;
}
// moving forward if not at this position
else {
tr = tr->link;
}
}

// printing found or not


if (found == 1) {
printf(
"Yes, %d is present in the linked list.\n",
key);
}
else {
printf("No, %d is not present in the linked "
"list.\n",
key);
}
}
}

// Driver Code
int main()
{
createList();
int choice;
while (1) {

printf("\n\t1 To see list\n");


printf("\t2 For insertion at"
" starting\n");
printf("\t3 For insertion at"
" end\n");
printf("\t4 For insertion at "
"any position\n");
printf("\t5 For deletion of "
"first element\n");
printf("\t6 For deletion of "
"last element\n");
printf("\t7 For deletion of "
"element at any position\n");
printf("\t8 To find maximum among"
" the elements\n");
printf("\t9 To find mean of "
"the elements\n");
printf("\t10 To sort element\n");
printf("\t11 To reverse the "
"linked list\n");
printf("\t12 Search an element in linked list\n");
printf("\t13 To exit\n");
printf("\nEnter Choice :\n");
scanf("%d", &choice);

switch (choice) {
case 1:
traverse();
break;
case 2:
insertAtFront();
break;
case 3:
insertAtEnd();
break;
case 4:
insertAtPosition();
break;
case 5:
deleteFirst();
break;
case 6:
deleteEnd();
break;
case 7:
deletePosition();
break;
case 8:
maximum();
break;
case 9:
mean();
break;
case 10:
sort();
break;
case 11:
reverseLL();
break;
case 12:
search();
break;
case 13:
exit(1);
break;
default:
printf("Incorrect Choice\n");
}
}
return 0;
}

13)C Program to Implement Circular Doubly Linked List


Solution:
#include<stdio.h>
#include<stdlib.h>

// structure of the node


struct node
{
struct node* prev;
int data;
struct node* next;
};

// global declaration of head node


struct node* head = NULL;

// function prototyping
struct node* create(int);
void insert_begin(int);
void insert_end(int);
void insert_mid(int, int);
void delete_begin();
void delete_end();
void delete_mid();
int search(int);
void update(int, int);
void sort();
int list_size();
void display();
void display_reverse(struct node*);
int get_data();
int get_position();

int main()
{
char user_active = 'Y';
int user_choice;
int data, position;

while(user_active == 'Y' || user_active == 'y')


{
printf("\n\n------ Circular Doubly Linked List -------\n");
printf("\n1. Insert a node at beginning");
printf("\n2. Insert a node at end");
printf("\n3. Insert a node at given position");
printf("\n\n4. Delete a node from beginning");
printf("\n5. Delete a node from end");
printf("\n6. Delete a node from given position");
printf("\n\n7. Print list from beginning");
printf("\n8. Print list from end");
printf("\n9. Search a node data");
printf("\n10. Update a node data");
printf("\n11. Sort the list");
printf("\n12. Exit");
printf("\n\n------------------------------\n");

printf("\nEnter your choice: ");


scanf("%d", &user_choice);
printf("\n------------------------------\n");
switch(user_choice)
{
case 1:
printf("\nInserting a node at beginning");
data = get_data();
insert_begin(data);
break;

case 2:
printf("\nInserting a node at end");
data = get_data();
insert_end(data);
break;

case 3:
printf("\nInserting a node at the given position");
data = get_data();
position = get_position();
insert_mid(position, data);
break;

case 4:
printf("\nDeleting a node from beginning\n");
delete_begin();
break;

case 5:
printf("\nDeleting a node from end\n");
delete_end();
break;

case 6:
printf("\nDelete a node from given position\n");
position = get_position();
delete_mid(position);
break;
case 7:
printf("\nPrinting the list from beginning\n\n");
display();
break;

case 8:
printf("\nPrinting the list from end\n\n");
if (head == NULL)
{
printf("\n\tList is Empty!\n");
} else {
display_reverse(head);
}
break;

case 9:
printf("\nSearching the node data");
data = get_data();
if (search(data) == 1) {
printf("\n\tNode Found\n");
} else {
printf("\n\tNode Not Found\n");
}
break;

case 10:
printf("\nUpdating the node data");
data = get_data();
position = get_position();
update(position, data);
break;

case 11:
sort();
printf("\nList was sorted\n");
break;
case 12:
printf("\nProgram was terminated\n\n");
return 0;

default:
printf("\n\tInvalid Choice\n");
}

printf("\n...............................\n");
printf("\nDo you want to continue? (Y/N) : ");
fflush(stdin);
scanf(" %c", &user_active);
}

return 0;
}

// creates a new node


struct node* create(int data)
{
struct node* new_node = (struct node*) malloc (sizeof(struct node));

if (new_node == NULL)
{
printf("\nMemory can't be allocated\n");
return NULL;
}

new_node->data = data;
new_node->next = NULL;
new_node->prev = NULL;

return new_node;
}

// insert a new node at the beginning of the list


void insert_begin(int data)
{
struct node* new_node = create(data);
if (new_node)
{
// if list is empty
if (head == NULL)
{
new_node->next = new_node;
new_node->prev = new_node;
head = new_node;
return;
}
head->prev->next = new_node;
new_node->prev = head->prev;
new_node->next = head;
head->prev = new_node;
head = new_node;
}
}

// inserts a new node at the end


void insert_end(int data)
{
struct node* new_node = create(data);

if (new_node)
{
if (head == NULL)
{
new_node->next = new_node;
new_node->prev = new_node;
head = new_node;
return;
}
head->prev->next = new_node;
new_node->prev = head->prev;
new_node->next = head;
head->prev = new_node;
}
}
// inserts node at the given position
void insert_mid(int position, int data)
{
// checking if the position is valid or not
if (position <= 0)
{
printf("\nInvalid Position\n");
} else if (head == NULL && position > 1) {
printf("\nInvalid Position\n");
} else if (head != NULL && position > list_size()) {
printf("\nInvalid Position\n");
} else if (position == 1) {
insert_begin(data);
} else {
struct node *new_node = create(data);

if (new_node != NULL) {
struct node *temp = head, *prev = NULL;
int i = 1;

// traverse the list to the given position


while (++i <= position) {
prev = temp;
temp = temp->next;
}

// update the prev node to the new noe


prev->next = new_node;

// update the new node to the temp (position node)


new_node->next = temp;
}
}
}

void delete_begin()
{
if (head == NULL) {
printf("\nList is Empty\n");
return;
} else if (head->next == head) {
free(head);
head = NULL;
return;
}

struct node* temp = head;


head->prev->next = head->next;
head->next->prev = head->prev;
head = head->next;

free(temp);
temp = NULL;
}

// deletes the node from the end of the list


void delete_end()
{
if (head == NULL) {
printf("\nList is Empty\n");
return;
} else if (head->next == head) {
free(head);
head = NULL;
return;
}

struct node* last_node = head->prev;

last_node->prev->next = head;
head->prev = last_node->prev;

free(last_node);
last_node = NULL;
}
// deletes the node from the given position
void delete_mid(int position)
{
if (position <= 0) {
printf("\n Invalid Position \n");
}
else if (position > list_size()) {
printf("\n Invalid position \n");
}
else if (position == 1) {
delete_begin();
}
else if (position == list_size()) {
delete_end();
}
else {
struct node *temp = head;
struct node *prev = NULL;
int i = 1;

while (i < position) {


prev = temp;
temp = temp->next;
i += 1;
}
prev->next = temp->next;
temp->next->prev = prev;
free(temp);
temp = NULL;
}
}

// search the node with the given key item


int search(int key)
{
if (head == NULL) {
printf("\n Not Found \n");
return 0;
}

struct node* temp = head;


do
{
if (temp->data == key) {
return 1;
}
temp = temp->next;
} while (temp != head);

return 0;
}

// updates the data of the given node position


void update(int position, int new_value)
{
if (head == NULL) {
printf("\n List is Empty \n");
return;
} else if (position <= 0 || position > list_size()) {
printf("\nInvalid position\n");
return;
}

struct node* temp = head;


int i = 0;

while (++i < position) {


temp = temp->next;
}
temp->data = new_value;
}

// sorts the linked list data using insertion sort


void sort()
{
if (head == NULL) {
printf("\nList is Empty\n");
return;
}
struct node* temp1 = head;
struct node* temp2 = head;
int key = 0, value;

do {
temp2 = temp1->next;

while(temp2 != head)
{
if (temp1->data > temp2->data)
{
value = temp1->data;
temp1->data = temp2->data;
temp2->data = value;
}
temp2 = temp2->next;
}
temp1 = temp1->next;
}while (temp1->next != head);

// display the list


void display()
{
if (head == NULL) {
printf("\nList is empty!\n");
return;
}

struct node* temp = head;


do {
printf("%d ", temp->data);
temp = temp->next;
} while (temp != head);
}

// display the list from end to start


void display_reverse(struct node* temp)
{
if (temp->next == head) {
printf("%d ", temp->data);
return;
}

display_reverse(temp->next);
printf("%d ", temp->data);
}

// calculate the size of the list


int list_size()
{
if (head == NULL) {
return 0;
}

struct node* temp = head;


int count = 0;

do {
count += 1;
temp = temp->next;
} while (temp != head);

return count;
}

int get_data()
{
int data;
printf("\n\nEnter Data: ");
scanf("%d", &data);

return data;
}

int get_position()
{
int position;
printf("\n\nEnter Position: ");
scanf("%d", &position);

return position;
}

14) C Program to Find the Largest Element in a Doubly Linked List

1. Solution: #include <stdio.h>


2. #include <stdlib.h>
3.
4. struct node
5. {
6. int num;
7. struct node *next;
8. struct node *prev;
9. };
10.
11. void create(struct node **);
12. int max(struct node *);
13. void release(struct node **);
14.
15. int main()
16. {
17. struct node *p = NULL;
18. int n;
19.
20. printf("Enter data into the list\n");
21. create(&p);
22. n = max(p);
23. printf("The maximum number entered in the list is %d.\n", n);
24. release (&p);
25.
26. return 0;
27. }
28.
29. int max(struct node *head)
30. {
31. struct node *max, *q;
32.
33. q = max = head;
34. while (q != NULL)
35. {
36. if (q->num > max->num)
37. {
38. max = q;
39. }
40. q = q->next;
41. }
42.
43. return (max->num);
44. }
45.
46. void create(struct node **head)
47. {
48. int c, ch;
49. struct node *temp, *rear;
50.
51. do
52. {
53. printf("Enter number: ");
54. scanf("%d", &c);
55. temp = (struct node *)malloc(sizeof(struct node));
56. temp->num = c;
57. temp->next = NULL;
58. temp->prev = NULL;
59. if (*head == NULL)
60. {
61. *head = temp;
62. }
63. else
64. {
65. rear->next = temp;
66. temp->prev = rear;
67. }
68. rear = temp;
69. printf("Do you wish to continue [1/0]: ");
70. scanf("%d", &ch);
71. } while (ch != 0);
72. printf("\n");
73. }
74.
75. void release(struct node **head)
76. {
77. struct node *temp = *head;
78. *head = (*head)->next;
79. while ((*head) != NULL)
80. {
81. free(temp);
82. temp = *head;
83. (*head) = (*head)->next;
84. }
85. }

15)C program to remove element from linked list


Solution:
#include <stdio.h>
#include <stdlib.h>

// A linked list node


struct Node {
int data;
struct Node* next;
};

/* Given a reference (pointer to pointer) to the head of a


list and an int, inserts a new node on the front of the
list. */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node
= (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}

/* Given a reference (pointer to pointer) to the head of a


list and a key, deletes the first occurrence of key in
linked list */
void deleteNode(struct Node** head_ref, int key)
{
// Store head node
struct Node *temp = *head_ref, *prev;

// If head node itself holds the key to be deleted


if (temp != NULL && temp->data == key) {
*head_ref = temp->next; // Changed head
free(temp); // free old head
return;
}

// Search for the key to be deleted, keep track of the


// previous node as we need to change 'prev->next'
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}

// If key was not present in linked list


if (temp == NULL)
return;

// Unlink the node from linked list


prev->next = temp->next;

free(temp); // Free memory


}

// This function prints contents of linked list starting


// from the given node
void printList(struct Node* node)
{
while (node != NULL) {
printf(" %d ", node->data);
node = node->next;
}
}

// Driver code
int main()
{
/* Start with the empty list */
struct Node* head = NULL;

push(&head, 7);
push(&head, 1);
push(&head, 3);
push(&head, 2);

puts("Created Linked List: ");


printList(head);
deleteNode(&head, 1);
puts("
Linked List after Deletion of 1: ");
printList(head);
return 0;
}

16) c programs polyniomial addition on linked list


Solution:

#include<stdio.h>
#include<stdlib.h>

struct Node
{
int coeff;
int pow;
struct Node* next;
};

void readPolynomial(struct Node** poly)


{
int coeff, exp, cont;
struct Node* temp = (struct
Node*)malloc(sizeof(struct Node));
*poly = temp;
do{
printf("\n Coeffecient: ");
scanf("%d", &coeff);
printf("\n Exponent: ");
scanf("%d", &exp);
temp->coeff = coeff;
temp->pow = exp;
temp-> next = NULL;
printf("\nHave more terms? 1 for y and 0
for no: ");
scanf("%d", &cont);
if(cont)
{
temp->next = (struct
Node*)malloc(sizeof(struct Node));
temp = temp->next;
temp->next = NULL;
}
}while(cont);
}

void displayPolynomial(struct Node* poly)


{
printf("\nPolynomial expression is: ");
while(poly != NULL)
{
printf("%dX^%d", poly->coeff, poly-
>pow);
poly = poly->next;
if(poly != NULL)
printf("+");
}
}

void addPolynomials(struct Node** result, struct Node*


first, struct Node* second)
{
struct Node* temp = (struct
Node*)malloc(sizeof(struct Node));
temp->next = NULL;
*result = temp;
while(first && second)
{
if(first->pow > second->pow)
{
temp->coeff = first->coeff;
temp->pow = first->pow;
first = first->next;
}
else if(first->pow < second->pow)
{
temp->coeff = second->coeff;
temp->pow = second->pow;
second = second->next;
}
else
{
temp->coeff = first->coeff + second-
>coeff;
temp->pow = first->pow;
first = first->next;
second = second->next;
}

if(first && second)


{
temp->next = (struct
Node*)malloc(sizeof(struct Node));
temp = temp->next;
temp->next = NULL;
}
}
while(first || second)
{
temp->next = (struct
Node*)malloc(sizeof(struct Node));
temp = temp->next;
temp->next = NULL;

if(first)
{
temp->coeff = first->coeff;
temp->pow = first->pow;
first = first->next;
}

else if(second)
{
temp->coeff = second->coeff;
temp->pow = second->pow;
second = second->next;
}
}
}

int main()
{

struct Node* first = NULL;


struct Node* second = NULL;
struct Node* result = NULL;

printf("\nEnter the corresponding data:-\n");


printf("\nFirst polynomial:\n");
readPolynomial(&first);
displayPolynomial(first);
printf("\nSecond polynomial:\n");
readPolynomial(&second);
displayPolynomial(second);
addPolynomials(&result, first, second);
displayPolynomial(result);
return 0;
}

17) C Program to Implement a queue using array

1. Solution: /*
2. * C Program to Implement a Queue using an Array
3. */
4. #include <stdio.h>
5.
6. #define MAX 50
7.
8. void insert();
9. void delete();
10. void display();
11. int queue_array[MAX];
12. int rear = - 1;
13. int front = - 1;
14. main()
15. {
16. int choice;
17. while (1)
18. {
19. printf("1.Insert element to queue \n");
20. printf("2.Delete element from queue \n");
21. printf("3.Display all elements of queue \n");
22. printf("4.Quit \n");
23. printf("Enter your choice : ");
24. scanf("%d", &choice);
25. switch (choice)
26. {
27. case 1:
28. insert();
29. break;
30. case 2:
31. delete();
32. break;
33. case 3:
34. display();
35. break;
36. case 4:
37. exit(1);
38. default:
39. printf("Wrong choice \n");
40. } /* End of switch */
41. } /* End of while */
42. } /* End of main() */
43.
44. void insert()
45. {
46. int add_item;
47. if (rear == MAX - 1)
48. printf("Queue Overflow \n");
49. else
50. {
51. if (front == - 1)
52. /*If queue is initially empty */
53. front = 0;
54. printf("Inset the element in queue : ");
55. scanf("%d", &add_item);
56. rear = rear + 1;
57. queue_array[rear] = add_item;
58. }
59. } /* End of insert() */
60.
61. void delete()
62. {
63. if (front == - 1 || front > rear)
64. {
65. printf("Queue Underflow \n");
66. return ;
67. }
68. else
69. {
70. printf("Element deleted from queue is : %d\n",
queue_array[front]);
71. front = front + 1;
72. }
73. } /* End of delete() */
74.
75. void display()
76. {
77. int i;
78. if (front == - 1)
79. printf("Queue is empty \n");
80. else
81. {
82. printf("Queue is : \n");
83. for (i = front; i <= rear; i++)
84. printf("%d ", queue_array[i]);
85. printf("\n");
86. }
87. } /* End of display() */

18) C Program to Implement priority queue using linked list


Solution:
#include <stdio.h>
#include <stdlib.h>

// Node
typedef struct node {
int data;

// Lower values indicate higher priority


int priority;

struct node* next;

} Node;

// Function to Create A New Node


Node* newNode(int d, int p)
{
Node* temp = (Node*)malloc(sizeof(Node));
temp->data = d;
temp->priority = p;
temp->next = NULL;

return temp;
}

// Return the value at head


int peek(Node** head)
{
return (*head)->data;
}

// Removes the element with the


// highest priority from the list
void pop(Node** head)
{
Node* temp = *head;
(*head) = (*head)->next;
free(temp);
}

// Function to push according to priority


void push(Node** head, int d, int p)
{
Node* start = (*head);

// Create new Node


Node* temp = newNode(d, p);

// Special Case: The head of list has lesser


// priority than new node. So insert new
// node before head node and change head node.
if ((*head)->priority > p) {

// Insert New Node before head


temp->next = *head;
(*head) = temp;
}
else {

// Traverse the list and find a


// position to insert new node
while (start->next != NULL &&
start->next->priority < p) {
start = start->next;
}

// Either at the ends of the list


// or at required position
temp->next = start->next;
start->next = temp;
}
}

// Function to check is list is empty


int isEmpty(Node** head)
{
return (*head) == NULL;
}

// Driver code
int main()
{
// Create a Priority Queue
// 7->4->5->6
Node* pq = newNode(4, 1);
push(&pq, 5, 2);
push(&pq, 6, 3);
push(&pq, 7, 0);

while (!isEmpty(&pq)) {
printf("%d ", peek(&pq));
pop(&pq);
}

return 0;
}
23) C program to implement preorder,postorder,inorder
Solution:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
node* left;
node* right;
};
struct node* root;
struct node* insert(struct node* r,int datatonode)
{
if(r = NULL)
{
r = (struct node*)malloc (sizeof(struct
node));
r->data = datatonode;
r->left = NULL;
r->right = NULL;
}
else if(datatonode < r->data)
r->left= insert(r->left,datatovalue);
else
r->rigth = insert(r->right,datatovalue);
return r;
}
void inOrder(struct node* r)
{
if(r!= NULL)
{
inOrder(r->left);
printf("%d",r->data);
inOrder(r->right);
}
}
void preOrder(struct node* r)
{
if(r!= NULL)
{
printf("%d",r->data);
preOrder(r->left);
preOrder(r->right);
}
}
void postOrder(struct node* r)
{
if(r!= NULL)
{
postOrder(r->left);
postOrder(r->right);
printf("%d",r->data);
}
}

int main()
{
root = NULL;
int number,value;
printf("entre the number of element to be inserted ?\n");
scanf("%d",&number);
for(int i=0;i<n;i++)
{
printf("Data no %d is",i+1);
scanf("%d",&value);
root = insert(root,value);
}
printf("========INRODER
TARVERSAL===========");
inOrder(root);
printf("\n");
printf("=======PREORDER
TRAVERSAL===========");
preOrder(root);
printf("\n");
printf("=======POSTORDRER
TRAVERSAL=========");
postOrder(root);
printf("\n");
getch();
return 0;
}

19) C program to search largest node


Solution:
1. #include <stdio.h>
2. #include <stdlib.h>
3. struct node
4. {
5. int info;
6. struct node *left, *right;
7. };
8. struct node *createnode(int key)
9. {
10. struct node *newnode = (struct node*)malloc(sizeof(struct node));
11. newnode->info = key;
12. newnode->left = NULL;
13. newnode->right = NULL;
14. return(newnode);
15. }
16. void inorder(struct node *root)
17. {
18. if(root != NULL)
19. {
20. inorder(root->left);
21. printf(" %d ",root->info);
22. inorder(root->right);
23. }
24. }
25. void smallest(struct node *root)
26. {
27. while(root != NULL && root->left != NULL)
28. {
29. root = root->left;
30. }
31. printf("\nSmallest value is %d\n", root->info);
32. }
33. void largest(struct node *root)
34. {
35. while (root != NULL && root->right != NULL)
36. {
37. root = root->right;
38. }
39. printf("\nLargest value is %d", root->info);
40. }
41. /*
42. * Main Function
43. */
44. int main()
45. {
46. /* Creating first Tree. */
47. struct node *newnode = createnode(25);
48. newnode->left = createnode(17);
49. newnode->right = createnode(35);
50. newnode->left->left = createnode(13);
51. newnode->left->right = createnode(19);
52. newnode->right->left = createnode(27);
53. newnode->right->right = createnode(55);
54. /* Sample Tree 1:
55. * 25
56. * / \
57. * 17 35
58. * /\ /\
59. * 13 19 27 55
60. */
61. printf("Inorder traversal of tree 1 :");
62. inorder(newnode);
63. largest(newnode);
64. smallest(newnode);
65.
66. /* Creating second Tree. */
67. struct node *node = createnode(1);
68. node->right = createnode(2);
69. node->right->right = createnode(3);
70. node->right->right->right = createnode(4);
71. node->right->right->right->right = createnode(5);
72. /* Sample Tree 2: Right Skewed Tree (Unbalanced).
73. * 1
74. * \
75. * 2
76. * \
77. * 3
78. * \
79. * 4
80. * \
81. * 5
82. */
83. printf("\nInorder traversal of tree 2 :");
84. inorder(node);
85. largest(node);
86. smallest(node);
87.
88. /* Creating third Tree. */
89. struct node *root = createnode(15);
90. /* Sample Tree 3- Tree having just one root node.
91. * 15
92. */
93. printf("\nInorder traversal of tree 3 :");
94. inorder(root);
95. largest(root);
96. smallest(root);
97. return 0;
98. }

20) C program to count number of nodes in binary tree


1. Solution: #include <stdio.h>
2. #include <stdlib.h>
3. struct node
4. {
5. int info;
6. struct node *left, *right;
7. };
8. struct node *createnode(int key)
9. {
10. struct node *newnode = (struct node*)malloc(sizeof(struct node));
11. newnode->info = key;
12. newnode->left = NULL;
13. newnode->right = NULL;
14. return(newnode);
15. }
16. static int count = 0;
17. int countnodes(struct node *root)
18. {
19. if(root != NULL)
20. {
21. countnodes(root->left);
22. count++;
23. countnodes(root->right);
24. }
25. return count;
26. }
27. /*
28. * Main Function
29. */
30. int main()
31. {
32. /* Creating first Tree. */
33. struct node *newnode = createnode(25);
34. newnode->left = createnode(27);
35. newnode->right = createnode(19);
36. newnode->left->left = createnode(17);
37. newnode->left->right = createnode(91);
38. newnode->right->left = createnode(13);
39. newnode->right->right = createnode(55);
40. /* Sample Tree 1:
41. * 25
42. * / \
43. * 27 19
44. * /\ /\
45. * 17 91 13 55
46. */
47. printf("Number of nodes in tree 1 = %d ",countnodes(newnode));
48. printf("\n");
49. count = 0;
50.
51. /* Creating second Tree. */
52. struct node *node = createnode(1);
53. node->right = createnode(2);
54. node->right->right = createnode(3);
55. node->right->right->right = createnode(4);
56. node->right->right->right->right = createnode(5);
57. /* Sample Tree 2: Right Skewed Tree (Unbalanced).
58. * 1
59. * \
60. * 2
61. * \
62. * 3
63. * \
64. * 4
65. * \
66. * 5
67. */
68. printf("Number of nodes in tree 2 = %d ",countnodes(node));
69. printf("\n");
70. count = 0;
71.
72. /* Creating third Tree. */
73. struct node *root = createnode(15);
74. /* Sample Tree 3- Tree having just one root node.
75. * 15
76. */
77. printf("Number of nodes in tree 3 = %d",countnodes(root));
78. return 0;
79. }

21) C program to implement min heap


1. Solution: #include<stdio.h>
2. #include<limits.h>
3.
4. /*Declaring heap globally so that we do not need to pass it as an
argument every time*/
5. /* Heap implemented here is Min Heap */
6.
7. int heap[1000000], heapSize;
8. /*Initialize Heap*/
9. void Init() {
10. heapSize = 0;
11. heap[0] = -INT_MAX;
12. }
13.
14. /*Insert an element into the heap */
15. void Insert(int element) {
16. heapSize++;
17. heap[heapSize] = element; /*Insert in the last place*/
18. /*Adjust its position*/
19. int now = heapSize;
20. while (heap[now / 2] > element) {
21. heap[now] = heap[now / 2];
22. now /= 2;
23. }
24. heap[now] = element;
25. }
26.
27. int DeleteMin() {
28. /* heap[1] is the minimum element. So we remove heap[1]. Size of
the heap is decreased.
29. Now heap[1] has to be filled. We put the last element in its place
and see if it fits.
30. If it does not fit, take minimum element among both its children and
replaces parent with it.
31. Again See if the last element fits in that place.*/
32. int minElement, lastElement, child, now;
33. minElement = heap[1];
34. lastElement = heap[heapSize--];
35. /* now refers to the index at which we are now */
36. for (now = 1; now * 2 <= heapSize; now = child) {
37. /* child is the index of the element which is minimum among both
the children */
38. /* Indexes of children are i*2 and i*2 + 1*/
39. child = now * 2;
40. /*child!=heapSize beacuse heap[heapSize+1] does not exist,
which means it has only one
41. child */
42. if (child != heapSize && heap[child + 1] < heap[child]) {
43. child++;
44. }
45. /* To check if the last element fits ot not it suffices to check if the
last element
46. is less than the minimum element among both the children*/
47. if (lastElement > heap[child]) {
48. heap[now] = heap[child];
49. } else /* It fits there */
50. {
51. break;
52. }
53. }
54. heap[now] = lastElement;
55. return minElement;
56. }
57.
58. int main() {
59. int number_of_elements;
60. printf("Program to demonstrate Heap:\nEnter the number of
elements: ");
61. scanf("%d", &number_of_elements);
62. int iter, element;
63. Init();
64. printf("Enter the elements: ");
65. for (iter = 0; iter < number_of_elements; iter++) {
66. scanf("%d", &element);
67. Insert(element);
68. }
69. for (iter = 0; iter < number_of_elements; iter++) {
70. printf("%d ", DeleteMin());
71. }
72. printf("\n");
73. return 0;
74. }

22) C program to implement max heap


Solution:
#include <stdio.h>
int main()
{
int arr[10], no, i, j, c, heap_root, temp;
printf("Input number of elements: ");
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];
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\t ", 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];
arr[heap_root] = arr[c];
arr[c] = temp;
}
heap_root = c;
} while (c < j);
}
printf("\nSorted array : ");
for (i = 0; i < no; i++)
printf("\t%d", arr[i]);
printf("\n");
}

23) C program to implement heapsort


1. Solution: #include<stdio.h>
2. #include <stdlib.h>
3. #define MAX 25
4.
5. void random_shuffle(int arr[])
6. {
7. int i, j, temp;
8. srand(time(NULL));
9. for (i = MAX - 1; i > 0; i--) {
10. j = rand()%(i + 1);
11. temp = arr[i];
12. arr[i] = arr[j];
13. arr[j] = temp;
14. }
15. }
16. void max_heapify(int a[], int i, int heapsize)
17. {
18. int tmp, largest;
19. int l = (2 * i) + 1;
20. int r = (2 * i) + 2;
21. if ((l <= heapsize) && (a[l] > a[i]))
22. largest = l;
23. else
24. largest = i;
25. if ((r <= heapsize) && (a[r] > a[largest]))
26. largest = r ;
27. if (largest != i)
28. {
29. tmp = a[i];
30. a[i] = a[largest];
31. a[largest] = tmp;
32. max_heapify(a, largest, heapsize);
33. }
34.
35. }
36. void build_max_heap(int a[], int heapsize)
37. {
38. int i;
39. for (i = heapsize/2; i >= 0; i--)
40. {
41. max_heapify(a, i, heapsize);
42. }
43.
44. }
45. void heap_sort(int a[], int heapsize)
46. {
47. int i, tmp;
48. build_max_heap(a, heapsize);
49. for (i = heapsize; i > 0; i--)
50. {
51. tmp = a[i];
52. a[i] = a[0];
53. a[0] = tmp;
54. heapsize--;
55. max_heapify(a, 0, heapsize);
56. }
57.
58. }
59. int main()
60. {
61. int i, r, heapsize;
62. int a[MAX];
63. for (i = 0; i < MAX; i++)
64. a[i] = i;
65. heapsize = MAX - 1;
66. random_shuffle(a);
67. printf("\n");
68. heap_sort(a, heapsize);
69. for (i = 0; i < MAX; i++)
70. printf("%d ", a[i]);
71. return 0;
72. }

24) C program to implement expression tree


Solution:
#include <stdio.h>
#include <stdlib.h>

/* A binary tree node has data, pointer to left child


and a pointer to right child */
struct node {
char data;
struct node* left;
struct node* right;
struct node* next;
};
struct node *head=NULL;
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(char data)
{
struct node* node
= (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
node->next = NULL;
return (node);
}
void printInorder(struct node* node)
{
if (node == NULL)
return;
else{
/* first recur on left child */
printInorder(node->left);

/* then print the data of node */


printf("%c ", node->data);

/* now recur on right child */


printInorder(node->right);
}
}

void push(struct node* x)


{
if(head==NULL)
head = x;
else
{
(x)->next = head;
head = x;
}
// struct node* temp;
// while(temp!=NULL)
// {
// printf("%c ", temp->data);
// temp = temp->next;
// }
}
struct node* pop()
{
// Popping out the top most[ pointed with head] element
struct node* p = head;
head = head->next;
return p;
}
int main()
{
char s[] = {'A','B','C','*','+','D','/'};
int l = sizeof(s) / sizeof(s[0]) ;
struct node *x, *y, *z;
for (int i = 0; i < l; i++) {
// if read character is operator then popping two
// other elements from stack and making a binary
// tree
if (s[i] == '+' || s[i] == '-' || s[i] == '*'
|| s[i] == '/' || s[i] == '^') {
z = newNode(s[i]);
x = pop();
y = pop();
z->left = y;
z->right = x;
push(z);
}
else {
z = newNode(s[i]);
push(z);
}
}
printf(" The Inorder Traversal of Expression Tree: ");
printInorder(z);
return 0;
}

25) C program to represent a graph using adjacency matrix


Solution:

#include <stdio.h>
// N vertices and M Edges
int N, M;

// Function to create Adjacency Matrix


void createAdjMatrix(int Adj[][N + 1],
int arr[][2])
{

// Initialise all value to this


// Adjacency list to zero
for (int i = 0; i < N + 1; i++) {

for (int j = 0; j < N + 1; j++) {


Adj[i][j] = 0;
}
}

// Traverse the array of Edges


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

// Find X and Y of Edges


int x = arr[i][0];
int y = arr[i][1];

// Update value to 1
Adj[x][y] = 1;
Adj[y][x] = 1;
}
}

// Function to print the created


// Adjacency Matrix
void printAdjMatrix(int Adj[][N + 1])
{

// Traverse the Adj[][]


for (int i = 1; i < N + 1; i++) {
for (int j = 1; j < N + 1; j++) {

// Print the value at Adj[i][j]


printf("%d ", Adj[i][j]);
}
printf("\n");
}
}

// Driver Code
int main()
{

// Number of vertices
N = 5;

// Given Edges
int arr[][2]
= { { 1, 2 }, { 2, 3 },
{ 4, 5 }, { 1, 5 } };

// Number of Edges
M = sizeof(arr) / sizeof(arr[0]);

// For Adjacency Matrix


int Adj[N + 1][N + 1];

// Function call to create


// Adjacency Matrix
createAdjMatrix(Adj, arr);

// Print Adjacency Matrix


printAdjMatrix(Adj);

return 0;
}
26) C program to implement bubble sort
1. Solution: #include <stdio.h>
2.
3. void bubble_sort(int arr[], int n) {
4. int i, j;
5. for (i = 0; i < n - 1; i++) {
6. for (j = 0; j < n - i - 1; j++) {
7. if (arr[j] > arr[j + 1]) {
8. int temp = arr[j];
9. arr[j] = arr[j + 1];
10. arr[j + 1] = temp;
11. }
12. }
13. }
14. }
15. int main() {
16. int arr[] = {64, 34, 25, 12, 22, 11, 90};
17. int n = sizeof(arr) / sizeof(arr[0]);
18. bubble_sort(arr, n);
19. printf("Sorted array: ");
20. for (int i = 0; i < n; i++) {
21. printf("%d ", arr[i]);
22. }
23. return 0;
24. }

27) C program to implement insertion sort


Solution:
#include <math.h>
#include <stdio.h>

/* Function to sort an array


using insertion sort*/
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;

/* Move elements of arr[0..i-1],


that are greater than key,
to one position ahead of
their current position */
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

// A utility function to print


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

// Driver code
int main()
{
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printArray(arr, n);

return 0;
}

28) C program to implement quick sort


Solution:
#include <stdio.h>

// Function to swap two elements


void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}

// Partition the array using the last element as the pivot


int partition(int arr[], int low, int high)
{
// Choosing the pivot
int pivot = arr[high];

// Index of smaller element and indicates


// the right position of pivot found so far
int i = (low - 1);

for (int j = low; j <= high - 1; j++) {

// If current element is smaller than the pivot


if (arr[j] < pivot) {

// Increment index of smaller element


i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}

// The main function that implements QuickSort


// arr[] --> Array to be sorted,
// low --> Starting index,
// high --> Ending index
void quickSort(int arr[], int low, int high)
{
if (low < high) {

// pi is partitioning index, arr[p]


// is now at right place
int pi = partition(arr, low, high);

// Separately sort elements before


// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

// Driver code
int main()
{
int arr[] = { 10, 7, 8, 9, 1, 5 };
int N = sizeof(arr) / sizeof(arr[0]);

// Function call
quickSort(arr, 0, N - 1);
printf("Sorted array: \n");
for (int i = 0; i < N; i++)
printf("%d ", arr[i]);
return 0;
}

29) C program to implement merge sort


Solution:
#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[]
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++;
}
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[], 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
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;
}

30) C program to implement selection sort


Solution: #include <stdio.h>
int main() {
int arr[10]={6,12,0,18,11,99,55,45,34,2};
int n=10;
int i, j, position, swap;
for (i = 0; i < (n - 1); i++) {
position = i;
for (j = i + 1; j < n; j++) {
if (arr[position] > arr[j])
position = j;
}
if (position != i) {
swap = arr[i];
arr[i] = arr[position];
arr[position] = swap;
}
}
for (i = 0; i < n; i++)
printf("%d\t", arr[i]);
return 0;
}

31) C program to implement Radix sort

Solution: #include<stdio.h>
int get_max (int a[], int n){
int max = a[0];
for (int i = 1; i < n; i++)
if (a[i] > max)
max = a[i];
return max;
}
void radix_sort (int a[], int n){
int bucket[10][10], bucket_cnt[10];
int i, j, k, r, NOP = 0, divisor = 1, lar, pass;
lar = get_max (a, n);
while (lar > 0){
NOP++;
lar /= 10;
}
for (pass = 0; pass < NOP; pass++){
for (i = 0; i < 10; i++){
bucket_cnt[i] = 0;
}
for (i = 0; i < n; i++){
r = (a[i] / divisor) % 10;
bucket[r][bucket_cnt[r]] = a[i];
bucket_cnt[r] += 1;
}
i = 0;
for (k = 0; k < 10; k++){
for (j = 0; j < bucket_cnt[k]; j++){
a[i] = bucket[k][j];
i++;
}
}
divisor *= 10;
printf ("After pass %d : ", pass + 1);
for (i = 0; i < n; i++)
printf ("%d ", a[i]);
printf ("
");
}
}
int main (){
int i, n, a[10];
printf ("Enter the number of items to be sorted: ");
scanf ("%d", &n);
printf ("Enter items: ");
for (i = 0; i < n; i++){
scanf ("%d", &a[i]);
}
radix_sort (a, n);
printf ("Sorted items : ");
for (i = 0; i < n; i++)
printf ("%d ", a[i]);
printf ("
");
return 0;
}

32) C program to implement linear search


Solution:
#include <stdio.h>
int main()
{
int a[10], i, item,n;
printf("\nEnter number of elements of an array:\n");
scanf("%d",&n);
printf("\nEnter elements: \n");
for (i=0; i<n; i++)
scanf("%d", &a[i]);
printf("\nEnter item to search: ");
scanf("%d", &item);
for (i=0; i<=9; i++)
if (item == a[i])
{
printf("\nItem found at location %d", i+1);
break;
}
if (i > 9)
printf("\nItem does not exist.");
return 0;
}

15) C program to implement binary search


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

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


scanf("%d", &n);

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

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


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

printf("Enter value to find\n");


scanf("%d", &search);

first = 0;
last = n - 1;
middle = (first+last)/2;

while (first <= last) {


if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;

middle = (first + last)/2;


}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);

return 0;
}
33) C program to implement modulo division

Solution:

// C Program to illustrate the working of modulo operator


#include <stdio.h>

int main(void)
{
int x, y;

int result;

x = 3;
y = 4;
// using modulo operator
result = x % y;
printf("%d", result);

result = y % x;
printf("\n%d", result);

// for different values


x = 4;
y = 2;
result = x % y;
printf("\n%d", result);

return 0;
}

34) C program to implement linear probe for collision

1. Solution: #include<stdio.h>
2. #include<stdlib.h>
3.
4. /* to store a data (consisting of key and value) in hash table array */
5. struct item
6. {
7. int key;
8. int value;
9. };
10.
11. /* each hash table item has a flag (status) and data (consisting of key
and value) */
12. struct hashtable_item
13. {
14.
15. int flag;
16. /*
17. * flag = 0 : data does not exist
18. * flag = 1 : data exists
19. * flag = 2 : data existed at least once
20. */
21.
22. struct item *data;
23.
24. };
25.
26. struct hashtable_item *array;
27. int size = 0;
28. int max = 10;
29.
30. /* initializing hash table array */
31. void init_array()
32. {
33. int i;
34. for (i = 0; i < max; i++)
35. {
36. array[i].flag = 0;
37. array[i].data = NULL;
38. }
39. }
40.
41. /* to every key, it will generate a corresponding index */
42. int hashcode(int key)
43. {
44. return (key % max);
45. }
46.
47. /* to insert an element in the hash table */
48. void insert(int key, int value)
49. {
50. int index = hashcode(key);
51. int i = index;
52.
53. /* creating new item to insert in the hash table array */
54. struct item *new_item = (struct item*) malloc(sizeof(struct item));
55. new_item->key = key;
56. new_item->value = value;
57.
58. /* probing through the array until we reach an empty space */
59. while (array[i].flag == 1)
60. {
61.
62. if (array[i].data->key == key)
63. {
64.
65. /* case where already existing key matches the given
key */
66. printf("\n Key already exists, hence updating its value
\n");
67. array[i].data->value = value;
68. return;
69.
70. }
71.
72. i = (i + 1) % max;
73. if (i == index)
74. {
75. printf("\n Hash table is full, cannot insert any more
item \n");
76. return;
77. }
78.
79. }
80.
81. array[i].flag = 1;
82. array[i].data = new_item;
83. size++;
84. printf("\n Key (%d) has been inserted \n", key);
85.
86. }
87.
88.
89. /* to remove an element from the hash table */
90. void remove_element(int key)
91. {
92. int index = hashcode(key);
93. int i = index;
94.
95. /* probing through array until we reach an empty space where not
even once an element had been present */
96. while (array[i].flag != 0)
97. {
98.
99. if (array[i].flag == 1 && array[i].data->key == key )
100. {
101.
102. // case when data key matches the given key
103. array[i].flag = 2;
104. array[i].data = NULL;
105. size--;
106. printf("\n Key (%d) has been removed \n",
key);
107. return;
108.
109. }
110. i = (i + 1) % max;
111. if (i == index)
112. {
113. break;
114. }
115.
116. }
117.
118. printf("\n This key does not exist \n");
119.
120. }
121.
122. /* to display all the elements of hash table */
123. void display()
124. {
125. int i;
126. for (i = 0; i < max; i++)
127. {
128. struct item *current = (struct item*) array[i].data;
129.
130. if (current == NULL)
131. {
132. printf("\n Array[%d] has no elements \n", i);
133. }
134. else
135. {
136. printf("\n Array[%d] has elements -: \n %d (key)
and %d(value) ", i, current->key, current->value);
137. }
138. }
139.
140. }
141.
142. int size_of_hashtable()
143. {
144. return size;
145. }
146.
147. void main()
148. {
149. int choice, key, value, n, c;
150. clrscr();
151.
152. array = (struct hashtable_item*) malloc(max *
sizeof(struct hashtable_item*));
153. init_array();
154.
155. do {
156. printf("Implementation of Hash Table in C
with Linear Probing \n\n");
157. printf("MENU-: \n1.Inserting item in the
Hashtable"
158. "\n2.Removing item from the Hashtable"
159. "\n3.Check the size of Hashtable"
160. "\n4.Display Hashtable"
161. "\n\n Please enter your choice-:");
162.
163. scanf("%d", &choice);
164.
165. switch(choice)
166. {
167.
168. case 1:
169.
170. printf("Inserting element in Hashtable\n");
171. printf("Enter key and value-:\t");
172. scanf("%d %d", &key, &value);
173. insert(key, value);
174.
175. break;
176.
177. case 2:
178.
179. printf("Deleting in Hashtable \n Enter the
key to delete-:");
180. scanf("%d", &key);
181. remove_element(key);
182.
183. break;
184.
185. case 3:
186.
187. n = size_of_hashtable();
188. printf("Size of Hashtable is-:%d\n", n);
189.
190. break;
191.
192. case 4:
193.
194. display();
195.
196. break;
197.
198. default:
199.
200. printf("Wrong Input\n");
201.
202. }
203.
204. printf("\n Do you want to continue-:(press 1 for
yes)\t");
205. scanf("%d", &c);
206.
207. }while(c == 1);
208.
209. getch();
210.
211. }

35) #include <stdio.h>


1. #include <stdlib.h>
2.
3. struct node {
4. int data;
5. struct node *right_child;
6. struct node *left_child;
7. };
8.
9. struct node* new_node(int x){
10. struct node *temp;
11. temp = malloc(sizeof(struct node));
12. temp->data = x;
13. temp->left_child = NULL;
14. temp->right_child = NULL;
15.
16. return temp;
17. }
18.
19. struct node* search(struct node * root, int x){
20. if (root == NULL || root->data == x)
21. return root;
22. else if (x > root->data)
23. return search(root->right_child, x);
24. else
25. return search(root->left_child, x);
26. }
27.
28. struct node* insert(struct node * root, int x){
29. if (root == NULL)
30. return new_node(x);
31. else if (x > root->data)
32. root->right_child = insert(root->right_child, x);
33. else
34. root -> left_child = insert(root->left_child, x);
35. return root;
36. }
37. struct node* find_minimum(struct node * root) {
38. if (root == NULL)
39. return NULL;
40. else if (root->left_child != NULL)
41. return find_minimum(root->left_child);
42. return root;
43. }
44.
45. struct node* delete(struct node * root, int x) {
46.
47. if (root == NULL)
48. return NULL;
49. if (x > root->data)
50. root->right_child = delete(root->right_child, x);
51. else if (x < root->data)
52. root->left_child = delete(root->left_child, x);
53. else {
54. if (root->left_child == NULL && root->right_child == NULL){
55. free(root);
56. return NULL;
57. }
58. else if (root->left_child == NULL || root->right_child == NULL){
59. struct node *temp;
60. if (root->left_child == NULL)
61. temp = root->right_child;
62. else
63. temp = root->left_child;
64. free(root);
65. return temp;
66. }
67. else {
68. struct node *temp = find_minimum(root->right_child);
69. root->data = temp->data;
70. root->right_child = delete(root->right_child, temp->data);
71. }
72. }
73. return root;
74. }
75.
76. void inorder(struct node *root){
77. if (root != NULL)
78. {
79. inorder(root->left_child);
80. printf(" %d ", root->data);
81. inorder(root->right_child);
82. }
83. }
84.
85. int main() {
86. struct node *root;
87. root = new_node(20);
88. insert(root, 5);
89. insert(root, 1);
90. insert(root, 15);
91. insert(root, 9);
92. insert(root, 7);
93. insert(root, 12);
94. insert(root, 30);
95. insert(root, 25);
96. insert(root, 40);
97. insert(root, 45);
98. insert(root, 42);
99.
100. inorder(root);
101. printf("\n");
102.
103. root = delete(root, 1);
104.
105. root = delete(root, 40);
106.
107. root = delete(root, 45);
108.
109. root = delete(root, 9);
110.
111. inorder(root);
112. printf("\n");
113.
114. return 0;
115. }

You might also like