Sorting and Searching Algorithms in C
Sorting and Searching Algorithms in C
ALGORITHM
CODE
#include <stdio.h>
int main()
{
int n;
// Input the size of the array
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n]; // Declare the array with size n
// Input the elements of the array
printf("Enter %d integers:\n", n);
for (int i = 0; i< n; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
}
// Bubble Sort algorithm
for (int i = 0; i< n - 1; i++) {
// Track whether a swap was made
int swapped = 0;
// Last i elements are already sorted
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] >arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = 1; // Set swapped to indicate a swap occurred
}
}
// If no two elements were swapped in the inner loop, then the array is sorted
if (swapped == 0) {
break;
}
}
return 0;
}
OUTPUT
Enter the number of elements in the array: 6
Enter 6 integers:
Element 1: 5
Element 2: 5
Element 3: 6
Element 4: 7
Element 5: 9
Element 6: 4
Sorted array:
455679
PROGRAM NO: 2
ALGORITHM
CODE
#include <stdio.h>
int main() {
int n;
// Input the size of the array
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n]; // Declare the array with size n
// Input the elements of the array
printf("Enter %d integers:\n", n);
for (int i = 0; i< n; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
}
// Swap the found minimum element with the first element of the unsorted part
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
OUTPUT
Enter the number of elements in the array: 5
Enter 5 integers:
Element 1: 34
Element 2: 45
Element 3: 56
Element 4: 67
Element 5: 78
Sorted array:
34 45 56 67 78
PROGRAM NO: 3
ALGORITHM
CODE
#include <stdio.h>
int main() {
int n;
// Partitioning process
for (int j = start; j < end; j++) {
if (arr[j] < pivot) {
i++; // Increment index of smaller element
// Swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Swap the pivot element with the element at i + 1
int temp = arr[i + 1];
arr[i + 1] = arr[end];
arr[end] = temp;
return 0;
}
OUTPUT
Enter the number of elements in the array: 5
Enter 5 integers:
Element 1: 98
Element 2: 87
Element 3: 67
Element 4: 76
Element 5: 45
Sorted array:
45 67 76 87 98
PROGRAM NO: 4
AIM:- Write a program to merge two sorted arrays using Merge Sort Technique.
ALGORITHM
ENTER (a[10],n)
1. Repeat step 2 for i = 0 to (n-1)
2. Input a[i]
3. Return
DISPLAY(c[20],p)
1. Repeat step 2 for k = 0 to p-1
2. Print c[k]
3. Return
MAIN( )
1. Start
2. Input no. of elements in 1st & 2nd array as ‘n’
& ‘m’
3. Enter (a.n)
4. Enter (b,m)
5. i = j = k = 0
6. Repeat step 7 to 12 while ((i < n)&&(j < m))
7. If (a[i] >= b[j]),goto step 9
8. c[k+1] = a[i+1]
9. If a[i] = b[j] ,goto step 11 10. c[k++] = b[j+
+] goto step 7 11. c[k++] = a[i++]
12. j++
13. Repeat step 14 while (i<n)
14. c[k++] = a[i++]
15. Repeat step 16 while m > j
16. c[k++] = b[j++]
17. Display merged arrays as display(c;k)
18. Exit
CODE
#include <stdio.h>
int main() {
int n1, n2;
// Input the size of the first sorted array
printf("Enter the number of elements in the first sorted array: ");
scanf("%d", &n1);
int arr1[n1]; // Declare the first sorted array
// Input the elements of the first sorted array
printf("Enter %d sorted integers for the first array:\n", n1);
for (inti = 0; i< n1; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &arr1[i]);
}
// Input the size of the second sorted array
printf("Enter the number of elements in the second sorted array: ");
scanf("%d", &n2);
int arr2[n2]; // Declare the second sorted array
// Input the elements of the second sorted array
printf("Enter %d sorted integers for the second array:\n", n2);
for (inti = 0; i< n2; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &arr2[i]);
}
// Merge the two sorted arrays
int merged[n1 + n2]; // Array to hold the merged result
inti = 0, j = 0, k = 0;
// Merge the arrays while there are elements in both
while (i< n1 && j < n2) {
if (arr1[i] <= arr2[j]) {
merged[k++] = arr1[i++];
} else {
merged[k++] = arr2[j++];
}
}
// If there are remaining elements in arr1
while (i< n1) {
merged[k++] = arr1[i++];
}
// If there are remaining elements in arr2
while (j < n2) {
merged[k++] = arr2[j++];
}
// Display the merged sorted array
printf("Merged sorted array:\n");
for (inti = 0; i< n1 + n2; i++) {
printf("%d ", merged[i]);
}
printf("\n");
return 0;
}
OUTPUT
Enter the number of elements in the first sorted array: 4
Enter 4 sorted integers for the first array:
Element 1: 34
Element 2: 54
Element 3: 67
Element 4: 78
Enter the number of elements in the second sorted array: 3
Enter 3 sorted integers for the second array:
Element 1: 4
Element 2: 7
Element 3: 8
Merged sorted array:
4 7 8 34 54 67 78
PROGRAM NO: 5
ALGORITHM
CODE
#include<stdio.h>
int main() {
int n, searchElement, found = 0;
if (!found) {
printf("Element %d not found in the array.\n", searchElement);
}
return 0;
}
OUTPUT
AIM:-Write programs for finding the element in the array using the Binary Search Technique.
ALGORITHM
1. low = 1,high = n
2. Repeat step 3 to 5 while low <= high
3. mid = (low + high)
4. If a[mid] = x
Print “ found at mid”
Return
5. If (a[mid] < x) low = mid + 1 Else
High = mid – 1
6. Print “x not found”
7. Exit
CODE
#include <stdio.h>
int main() {
int n, searchElement, left, right, middle;
if (arr[middle] == searchElement) {
printf("Element %d found at index %d.\n", searchElement, middle);
found = 1; // Set found flag
break; // Exit the loop if found
} else if (arr[middle] <searchElement) {
left = middle + 1; // Search in the right half
} else {
right = middle - 1; // Search in the left half
}
}
if (!found) {
printf("Element %d not found in the array.\n", searchElement);
}
return 0;
}
OUTPUT
Enter the number of elements in the sorted array: 4
Enter 4 sorted integers:
Element 1: 45
Element 2: 56
Element 3: 76
Element 4: 87
Enter the element to search for: 46
Element 46 not found in the array.
PROGRAM NO: 7
ALGORITHM
INSERTION
PUSH(item)
1. If (item = max of stack)
Print “overflow”
Return
2. top = top + 1
3. stack[top] = item 4. Return
DELETION
POP(item)
1. If (top = - 1)
Print “underflow”
Return
2. Item = stack[top]
3. top = top – 1
4. Return
DISPLAY
1. If top = - 1
Print “underflow”
2. repeat step 3 for i = top to i >= 0
3. Print stack[i] 4. Return
CODE
#include <stdio.h>
#include <stdlib.h>
#define MAX 100 // Maximum size of the stack
// Stack structure
struct Stack {
int arr[MAX];
int top;
};
// Function to initialize the stack
void initStack(struct Stack* stack) {
stack->top = -1; // Stack is initially empty
}
// Function to check if the stack is full
int isFull(struct Stack* stack) {
return stack->top == MAX - 1;
}
// Function to check if the stack is empty
int isEmpty(struct Stack* stack) {
return stack->top == -1;
}
// Function to push an element onto the stack
void push(struct Stack* stack, int value) {
if (isFull(stack)) {
printf("Stack Overflow! Cannot push %d\n", value);
} else {
stack->arr[++stack->top] = value;
printf("%d pushed onto stack.\n", value);
}
}
// Function to pop an element from the stack
int pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack Underflow! Cannot pop from an empty stack.\n");
return -1; // Return -1 to indicate stack is empty
} else {
return stack->arr[stack->top--];
}
}
OUTPUT
Menu:
1. Push
2. Pop
3. Display Stack
4. Check if Stack is Empty
5. Exit
Enter your choice: 1
Enter value to push: 10
10 pushed onto stack.
Menu:
1. Push
2. Pop
3. Display Stack
4. Check if Stack is Empty
5. Exit
Enter your choice: 1
Enter value to push: 20
20 pushed onto stack.
Menu:
1. Push
2. Pop
3. Display Stack
4. Check if Stack is Empty
5. Exit
Enter your choice: 3
Stack elements: 20 10
Menu:
1. Push
2. Pop
3. Display Stack
4. Check if Stack is Empty
5. Exit
Enter your choice: 2
20 popped from stack.
Menu:
1. Push
2. Pop
3. Display Stack
4. Check if Stack is Empty
5. Exit
Enter your choice: 3
Stack elements: 10
Menu:
1. Push
2. Pop
3. Display Stack
4. Check if Stack is Empty
5. Exit
Enter your choice: 4
Stack is not empty.
Menu:
1. Push
2. Pop
3. Display Stack
4. Check if Stack is Empty
5. Exit
Enter your choice: 2
10 popped from stack.
Menu:
1. Push
2. Pop
3. Display Stack
4. Check if Stack is Empty
5. Exit
Enter your choice: 4
Stack is empty.
Menu:
1. Push
2. Pop
3. Display Stack
4. Check if Stack is Empty
5. Exit
Enter your choice: 5
Exiting...
PROGRAM NO: 8
AIM:- Write a menu driven program to implement stack using Linked List.
ALGORITHM
PUSH( )
1. t = newnode( )
2. Enter info to be inserted
3. Read n
4. t info = n
5. t next = top
6. top = t
7. Return
POP( )
1. If (top = NULL)
Print “ underflow”
Return
2. x = top
3. top = top next
4. delnode(x)
5. Return
CODE
#include <stdio.h>
#include <stdlib.h>
// Stack structure
struct Stack {
struct Node* top;
};
// Function to initialize the stack
void initStack(struct Stack* stack) {
stack->top = NULL; // Stack is initially empty
}
// Main function
int main() {
struct Stack stack;
initStack(&stack);
int choice, value;
do {
printf("\nMenu:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display Stack\n");
printf("4. Check if Stack is Empty\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to push: ");
scanf("%d", &value);
push(&stack, value);
break;
case 2:
value = pop(&stack);
if (value != -1) {
printf("%d popped from stack.\n", value);
}
break;
case 3:
display(&stack);
break;
case 4:
if (isEmpty(&stack)) {
printf("Stack is empty.\n");
} else {
printf("Stack is not empty.\n");
}
break;
case 5:
printf("Exiting...\n");
break;
default:
printf("Invalid choice! Please try again.\n");
}
} while (choice != 5);
return 0;
}
OUTPUT
Menu:
1. Push
2. Pop
3. Display Stack
4. Check if Stack is Empty
5. Exit
Enter your choice: 1
Enter value to push: 23
23 pushed onto stack.
Menu:
1. Push
2. Pop
3. Display Stack
4. Check if Stack is Empty
5. Exit
Enter your choice: 1
Enter value to push: 60
60 pushed onto stack.
Menu:
1. Push
2. Pop
3. Display Stack
4. Check if Stack is Empty
5. Exit
Enter your choice: 3
Stack elements: 60 23
Menu:
1. Push
2. Pop
3. Display Stack
4. Check if Stack is Empty
5. Exit
Enter your choice: 2
60 popped from stack.
Menu:
1. Push
2. Pop
3. Display Stack
4. Check if Stack is Empty
5. Exit
Enter your choice: 3
Stack elements: 23
Menu:
1. Push
2. Pop
3. Display Stack
4. Check if Stack is Empty
5. Exit
Enter your choice: 4
Stack is not empty.
Menu:
1. Push
2. Pop
3. Display Stack
4. Check if Stack is Empty
5. Exit
Enter your choice: 2
23 popped from stack.
Menu:
1. Push
2. Pop
3. Display Stack
4. Check if Stack is Empty
5. Exit
Enter your choice: 4
Stack is empty.
Menu:
1. Push
2. Pop
3. Display Stack
4. Check if Stack is Empty
5. Exit
Enter your choice: 5
Exiting...
PROGRAM NO: 9
ALGORITHM
P postfix expression
1. Add a right parenthesis “)” at the end of P
2. Scan P from left to right and repeat steps 3 & 4
until sentinel “)” is encountered
3. If an operand is encountered, put it on stack
4. 4. If an operator is encountered , then:
a) Remove the top two elements of stack , where A is the top element &
B is the next to top element b) Evaluate B A
c) Place the result of (b) back on stack
5. Set value equal to the top element on stack
6. Exit
CODE
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
// Stack structure
struct Stack {
int arr[MAX];
int top;
};
int result;
switch (expression[i]) {
case '+':
result = leftOperand + rightOperand;
break;
case '-':
result = leftOperand - rightOperand;
break;
case '*':
result = leftOperand * rightOperand;
break;
case '/':
if (rightOperand == 0) {
printf("Error: Division by zero.\n");
return -1; // Error condition
}
result = leftOperand / rightOperand;
break;
default:
printf("Error: Invalid operator %c\n", expression[i]);
return -1; // Error condition
}
push(&stack, result);
}
i++;
}
return pop(&stack); // The final result will be the only element left in the stack
}
// Main function
int main() {
char expression[MAX];
return 0;
}
OUTPUT
Enter a postfix expression (e.g., 5 6 2 + * 12 4 / -): 5 6 2 + * 12 4 / -
Result: 37
PROGRAM NO: 10
ALGORITHM
Q arithmetic expression
P postfix expression
1. Push “(“ onto stack, and add “)” to the end of Q
2. Scan Q from left to right and repeat steps 3 to 6 for each element of
Q untill the stack is empty
3. If an operand is encountered , add it to P
4. If a left parenthesis is encountered, push it onto stack 5. If an
operator is encountered , then:
(a) Repeatedly pop from stack and add to P each operator
which has the same precedence as or higher precedence
than
(b) Add to stack
6. If a right parenthesis is encountered, then:
(a) Repeatedly pop from stack and add to P each operator until a left
parenthesis is encountered (b) Remove the left parenthesis
7. Exit
CODE
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX 100 // Maximum size for the stack and expression
// Stack structure
struct Stack {
char arr[MAX];
int top;
};
// Main function
int main() {
char infix[MAX], postfix[MAX];
printf("Enter an infix expression (e.g., A + B * C): ");
fgets(infix, sizeof(infix), stdin);
infix[strcspn(infix, "\n")] = 0; // Remove trailing newline
infixToPostfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
return 0;
}
OUTPUT
Enter an infix expression (e.g., A + B * C): A + B * C
Postfix expression: ABC*+
PROGRAM NO: 11
AIM:- Write a menu driven program to implement queue using Linked List.
ALGORITHM
CREATE
1. t = new node
2. Enter info to be inserted
3. Read n
4. t info = n
5. t next = front 6. front = t
INSERTION
1. r next = t
2. t next = NULL
3. Return
DELETION
1. x = front
2. front = front next
3. delnode(x) 4. Return
DISPLAY
1. If (front = NULL)
Print “ empty queue”
Return
Else
P = start
Repeat until (p<> NULL)
Print p info
P = p next
Return
Program
CODE
#include <stdio.h>
#include <stdlib.h>
// Main function
int main() {
struct Queue* queue = createQueue();
int choice, data;
while (1) {
printf("\nMenu:\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Display Queue\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the value to enqueue: ");
scanf("%d", &data);
enqueue(queue, data);
break;
case 2:
dequeue(queue);
break;
case 3:
displayQueue(queue);
break;
case 4:
printf("Exiting the program.\n");
free(queue); // Free the queue structure
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}
OUTPUT
Menu:
1. Enqueue
2. Dequeue
3. Display Queue
4. Exit
Enter your choice: 1
Enter the value to enqueue: 10
10 enqueued to queue
Menu:
1. Enqueue
2. Dequeue
3. Display Queue
4. Exit
Enter your choice: 1
Enter the value to enqueue: 20
20 enqueued to queue
Menu:
1. Enqueue
2. Dequeue
3. Display Queue
4. Exit
Enter your choice: 3
Queue: 10 20
Menu:
1. Enqueue
2. Dequeue
3. Display Queue
4. Exit
Enter your choice: 2
10 dequeued from queue
Menu:
1. Enqueue
2. Dequeue
3. Display Queue
4. Exit
Enter your choice: 3
Queue: 20
Menu:
1. Enqueue
2. Dequeue
3. Display Queue
4. Exit
Enter your choice: 4
Exiting the program.
PROGRAM NO: 12
AIM:- Write a Menu Driven Program to implement various operation of Singly Linked List.
ALGORITHM
1. t = newmode( )
2. Enter info to be inserted
3. Read n
4. t info = n
5. t next = start
6. Start = t
INSERTION
BEGIN
1. t next = start
2. start = t
Return
MIDDLE
1. Enter info of the node after which new node
to be inserted
2. Read x
3. p = start
4. Repeat step 5 until p info <> x
5. p = p next
6. t next = p next
7. p next = t
8. Return
LAST
1. p = start
2. Repeat step 3 until p next NULL
3. p = p next
4. t next = NULL
5. p next = t
6. Return
DELETION
BEGIN
1. x = start
2. start = start next
3. delnode(x)
MIDDLE
1. Enter the info of node to be deleted
2. Read n
3. p = start
4. c = start
5. while (c info <> NULL) p = c c = c
next 6. p next = c next
7. delnode ( c )
8. Return
LAST
1. p = start c = start
2. while (c next <>
NULL)
p = c c = c next 3. p
next = c next
4. delnode ( c)
5. Return
TRAVERSAL
1. p = start
2. while (p <> NULL) Print p info
P=p next
3. Return
CODE
#include <stdio.h>
#include <stdlib.h>
// Main function
int main() {
struct Node* head = NULL;
int choice, data;
while (1) {
printf("\nMenu:\n");
printf("1. Insert at Beginning\n");
printf("2. Insert at End\n");
printf("3. Delete Node\n");
printf("4. Display List\n");
printf("5. Search Element\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the value to insert at the beginning: ");
scanf("%d", &data);
insertAtBeginning(&head, data);
break;
case 2:
printf("Enter the value to insert at the end: ");
scanf("%d", &data);
insertAtEnd(&head, data);
break;
case 3:
printf("Enter the value to delete: ");
scanf("%d", &data);
deleteNode(&head, data);
break;
case 4:
displayList(head);
break;
case 5:
printf("Enter the value to search: ");
scanf("%d", &data);
searchElement(head, data);
break;
case 6:
printf("Exiting the program.\n");
// Free the linked list
while (head != NULL) {
struct Node* temp = head;
head = head->next;
free(temp);
}
exit(0);
}
}
}
OUTPUT
Menu:
1. Insert at Beginning
2. Insert at End
3. Delete Node
4. Display List
5. Search Element
6. Exit
Enter your choice: 1
Enter the value to insert at the beginning: 10
10 inserted at the beginning.
Menu:
1. Insert at Beginning
2. Insert at End
3. Delete Node
4. Display List
5. Search Element
6. Exit
Enter your choice: 2
Enter the value to insert at the end: 20
20 inserted at the end.
Menu:
1. Insert at Beginning
2. Insert at End
3. Delete Node
4. Display List
5. Search Element
6. Exit
Enter your choice: 4
Linked List: 10 -> 20 -> NULL
Menu:
1. Insert at Beginning
2. Insert at End
3. Delete Node
4. Display List
5. Search Element
6. Exit
Enter your choice: 3
Enter the value to delete: 10
10 deleted from the list.
Menu:
1. Insert at Beginning
2. Insert at End
3. Delete Node
4. Display List
5. Search Element
6. Exit
Enter your choice: 4
Linked List: 20 -> NULL
Menu:
1. Insert at Beginning
2. Insert at End
3. Delete Node
4. Display List
5. Search Element
6. Exit
Enter your choice: 5
Enter the value to search: 20
20 found in the list.
Menu:
1. Insert at Beginning
2. Insert at End
3. Delete Node
4. Display List
5. Search Element
6. Exit
Enter your choice: 6
Exiting the program.
PROGRAM NO: 13
AIM:-Write a Menu Driven Program to implement various operation of Doubly Linked List.
ALGORITHM
1. t = new node
2. Enter “the info to be inserted”
3. Read n
4. t info = n
5. t next = NULL 6. t prev NULL
INSERTION
BEGIN
1. If start = NULL start = t
2. else
t next = NULL t
next prev = t
start = t
Return
MIDDLE
1. Print “ enter info of the node after which you
want to insert”
2. Read x
3. p = start
4. Repeat while p<> NULL If (p info = n) t
next = p next p next = t t
prev = p p next prev = t
Return
Else
P = p next
5. Print x not found
t next = NULL p
next = t
DELETION
BEGIN
1. p = start
2. p next prev = NULL
3. start = p next
4. start = p next
5. delnode(p)
6. Return
MIDDLE
1. Enter “info of the node to be deleted”
2. Read x
3. p = start
4. Repeat until p<> NULL If(p info = x)
p prev next = p
next p next prev = p
prev delnode(p) Return
Else
P = p next
5. Print “x not found”
LAST
1. P = start
2. Repeat while p<> NULL
If(p next = NULL)
Delnode(p)
3. Return
DISPLAY
1. p = start
2. Repeat while p <> NULL
Print p info
P=p next
CODE
#include <stdio.h>
#include <stdlib.h>
while (1) {
printf("\nMenu:\n");
printf("1. Insert at Beginning\n");
printf("2. Insert at End\n");
printf("3. Delete Node\n");
printf("4. Display List\n");
printf("5. Search Element\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the value to insert at the beginning: ");
scanf("%d", &data);
insertAtBeginning(&head, data);
break;
case 2:
printf("Enter the value to insert at the end: ");
scanf("%d", &data);
insertAtEnd(&head, data);
break;
case 3:
printf("Enter the value to delete: ");
scanf("%d", &data);
deleteNode(&head, data);
break;
case 4:
displayList(head);
break;
case 5:
printf("Enter the value to search: ");
scanf("%d", &data);
searchElement(head, data);
break;
case 6:
printf("Exiting the program.\n");
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
OUTPUT
Menu:
1. Insert at Beginning
2. Insert at End
3. Delete Node
4. Display List
5. Search Element
6. Exit
Enter your choice: 1
Enter the value to insert at the beginning: 10
10 inserted at the beginning.
Menu:
1. Insert at Beginning
2. Insert at End
3. Delete Node
4. Display List
5. Search Element
6. Exit
Enter your choice: 2
Enter the value to insert at the end: 20
20 inserted at the end.
Menu:
1. Insert at Beginning
2. Insert at End
3. Delete Node
4. Display List
5. Search Element
6. Exit
Enter your choice: 4
Doubly Linked List: 10 <-> 20 <-> NULL
Menu:
1. Insert at Beginning
2. Insert at End
3. Delete Node
4. Display List
5. Search Element
6. Exit
Enter your choice: 3
Enter the value to delete: 10
10 deleted from the list.
Menu:
1. Insert at Beginning
2. Insert at End
3. Delete Node
4. Display List
5. Search Element
6. Exit
Enter your choice: 4
Doubly Linked List: 20 <-> NULL
Menu:
1. Insert at Beginning
2. Insert at End
3. Delete Node
4. Display List
5. Search Element
6. Exit
Enter your choice: 5
Enter the value to search: 20
20 found in the list.
Menu:
1. Insert at Beginning
2. Insert at End
3. Delete Node
4. Display List
5. Search Element
6. Exit
Enter your choice: 6
Exiting the program.
PROGRAM NO: 14
ALGORITHM
INSERTION
1. t = newnode
2. t -> info = n
3. t -> left = t -> right = NULL 4. If (root =
NULL) root = t return 5. ptr = root
6. Repeat step 7 until ptr = NULL
7. If (ptr -> info > n)
If (ptr -> left = NULL)
Ptr ->left = t
Return
Else
Ptr = ptr -> left
Else
If (ptr ->right = NULL)
Ptr ->right = t
Return
Else
Ptr = ptr -> right
DELETION
1. If (root = NULL)
Print “Empty tree “
Return
2. ptr = root, par = NULL
3. Repeat step 4 & 5 until (ptr info = n or ptr
= NULL)
4. par = ptr
5. If (ptr-> info > n) ptr = ptr ->left Else
Ptr = ptr ->right 6.
If ptr = NULL
print “ no. not present”
CODE
#include <stdio.h>
#include <stdlib.h>
// Node with two children: Get the inorder successor (smallest in the right subtree)
struct Node* temp = findMin(root->right);
root->data = temp->data; // Copy the inorder successor's content to this node
root->right = deleteNode(root->right, temp->data); // Delete the inorder successor
}
return root;
}
// Main function
int main() {
struct Node* root = NULL;
int choice, data;
while (1) {
printf("\nMenu:\n");
printf("1. Insert\n");
printf("2. Search\n");
printf("3. Delete\n");
printf("4. In-order Traversal\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the value to insert: ");
scanf("%d", &data);
root = insert(root, data);
printf("%d inserted into the BST.\n", data);
break;
case 2:
printf("Enter the value to search: ");
scanf("%d", &data);
struct Node* foundNode = search(root, data);
if (foundNode != NULL) {
printf("%d found in the BST.\n", data);
} else {
printf("%d not found in the BST.\n", data);
}
break;
case 3:
printf("Enter the value to delete: ");
scanf("%d", &data);
root = deleteNode(root, data);
printf("%d deleted from the BST.\n", data);
break;
case 4:
printf("In-order Traversal: ");
inorderTraversal(root);
printf("\n");
break;
case 5:
printf("Exiting the program.\n");
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
OUTPUT
Menu:
1. Insert
2. Search
3. Delete
4. In-order Traversal
5. Exit
Enter your choice: 1
Enter the value to insert: 50
50 inserted into the BST.
Menu:
1. Insert
2. Search
3. Delete
4. In-order Traversal
5. Exit
Enter your choice: 1
Enter the value to insert: 25
30 inserted into the BST.
Menu:
1. Insert
2. Search
3. Delete
4. In-order Traversal
5. Exit
Enter your choice: 1
Enter the value to insert: 73
70 inserted into the BST.
Menu:
1. Insert
2. Search
3. Delete
4. In-order Traversal
5. Exit
Enter your choice: 4
In-order Traversal: 25 50 73
Menu:
1. Insert
2. Search
3. Delete
4. In-order Traversal
5. Exit
Enter your choice: 2
Enter the value to search: 25
30 found in the BST.
Menu:
1. Insert
2. Search
3. Delete
4. In-order Traversal
5. Exit
Enter your choice: 3
Enter the value to delete: 25
30 deleted from the BST.
Menu:
1. Insert
2. Search
3. Delete
4. In-order Traversal
5. Exit
Enter your choice: 4
In-order Traversal: 50 73
Menu:
1. Insert
2. Search
3. Delete
4. In-order Traversal
5. Exit
Enter your choice: 5
Exiting the program.
PROGRAM NO: 15
ALGORITHM
Preorder(root)
If root = null then exit
Process root->info
Preorder root->left;
Preorder root->right
Exit
Inorder(root)
If root = null then exit
Inorder root->left
Process root->info
Inorder root->right
Exit
Postorder(root)
If root = null then exit
Postorder root->left
Postorder root->right
Postorder root->info exit
CODE
#include <stdio.h>
#include <stdlib.h>
queue[rear++] = root;
if (current->left != NULL) {
queue[rear++] = current->left;
}
if (current->right != NULL) {
queue[rear++] = current->right;
}
}
// Main function
int main() {
// Creating a simple binary tree
struct Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);
OUTPUT
In-order Traversal: 4 2 5 1 6 3 7
Pre-order Traversal: 1 2 4 5 3 6 7
Post-order Traversal: 4 5 2 6 7 3 1
Level-order Traversal: 1 2 3 4 5 6 7
ADDED PRACTICALS
PROGRAM NO: 1
AIM:- Write a program to perform following operations on matrix using functions - Addition,
Subtraction, Multiplication, and Transpose.
ALGORITHM
Matmul(a,b,m,n,p)
1 for(i=1 to m)
2 for(j = 1 to p)
3 c[i][j] =0;
4 for(k= 1to n)
5 c[i][j] = c[i][j]+a[i][j]*b[i][j]
6 exit
CODE
#include <stdio.h>
#define MAX 10 // Maximum size of the matrix
// Function prototypes
void inputMatrix(int matrix[MAX][MAX], int rows, int cols);
void displayMatrix(int matrix[MAX][MAX], int rows, int cols);
void addMatrices(int a[MAX][MAX], int b[MAX][MAX], int result[MAX][MAX], int rows, int cols);
void subtractMatrices(int a[MAX][MAX], int b[MAX][MAX], int result[MAX][MAX], int rows, int
cols);
void multiplyMatrices(int a[MAX][MAX], int b[MAX][MAX], int result[MAX][MAX], int rowsA, int
colsA, int colsB);
void transposeMatrix(int matrix[MAX][MAX], int result[MAX][MAX], int rows, int cols);
int main() {
int a[MAX][MAX], b[MAX][MAX], result[MAX][MAX];
int rowsA, colsA, rowsB, colsB;
int choice;
do {
printf("\nMenu:\n");
printf("1. Add Matrices\n");
printf("2. Subtract Matrices\n");
printf("3. Multiply Matrices\n");
printf("4. Transpose First Matrix\n");
printf("5. Transpose Second Matrix\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
if (rowsA == rowsB && colsA == colsB) {
addMatrices(a, b, result, rowsA, colsA);
printf("Result of Addition:\n");
displayMatrix(result, rowsA, colsA);
} else {
printf("Matrices must be of the same dimensions for addition.\n");
}
break;
case 2:
if (rowsA == rowsB && colsA == colsB) {
subtractMatrices(a, b, result, rowsA, colsA);
printf("Result of Subtraction:\n");
displayMatrix(result, rowsA, colsA);
} else {
printf("Matrices must be of the same dimensions for subtraction.\n");
}
break;
case 3:
if (colsA == rowsB) {
multiplyMatrices(a, b, result, rowsA, colsA, colsB);
printf("Result of Multiplication:\n");
displayMatrix(result, rowsA, colsB);
} else {
printf("Number of columns in the first matrix must equal the number of rows in the second
matrix for multiplication.\n");
}
break;
case 4:
transposeMatrix(a, result, rowsA, colsA);
printf("Transpose of First Matrix:\n");
displayMatrix(result, colsA, rowsA);
break;
case 5:
transposeMatrix(b, result, rowsB, colsB);
printf("Transpose of Second Matrix:\n");
displayMatrix(result, colsB, rowsB);
break;
case 6:
printf("Exiting the program.\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 6);
return 0;
}
// Function to input a matrix
void inputMatrix(int matrix[MAX][MAX], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}
}
OUTPUT
Enter the number of rows and columns for the first matrix: 2 2
Enter elements of the first matrix:
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [1][0]: 3
Enter element [1][1]: 4
Enter the number of rows and columns for the second matrix: 2 2
Enter elements of the second matrix:
Enter element [0][0]: 5
Enter element [0][1]: 6
Enter element [1][0]: 7
Enter element [1][1]: 8
Menu:
1. Add Matrices
2. Subtract Matrices
3. Multiply Matrices
4. Transpose First Matrix
5. Transpose Second Matrix
6. Exit
Enter your choice: 1
Result of Addition:
68
10 12
Menu:
1. Add Matrices
2. Subtract Matrices
3. Multiply Matrices
4. Transpose First Matrix
5. Transpose Second Matrix
6. Exit
Enter your choice: 2
Result of Subtraction:
-4 -4
-4 -4
Menu:
1. Add Matrices
2. Subtract Matrices
3. Multiply Matrices
4. Transpose First Matrix
5. Transpose Second Matrix
6. Exit
Enter your choice: 3
Result of Multiplication:
19 22
43 50
Menu:
1. Add Matrices
2. Subtract Matrices
3. Multiply Matrices
4. Transpose First Matrix
5. Transpose Second Matrix
6. Exit
Enter your choice: 4
Menu:
1. Add Matrices
2. Subtract Matrices
3. Multiply Matrices
4. Transpose First Matrix
5. Transpose Second Matrix
6. Exit
Enter your choice: 5
Menu:
1. Add Matrices
2. Subtract Matrices
3. Multiply Matrices
4. Transpose First Matrix
5. Transpose Second Matrix
6. Exit
Enter your choice: 6
ALGORITHM
1. Initialize Buckets:
Determine the number of buckets based on the array size.
Create an array of empty buckets.
2. Distribute Elements into Buckets:
Calculate the index for each element in the array by mapping the element’s value to its
corresponding bucket.
Place each element in its respective bucket.
3. Sort Each Bucket:
1. Sort each bucket individually. Use a sorting algorithm like Insertion Sort for each bucket,
which is efficient for small sizes.
4. Concatenate Buckets:
2. Combine all sorted buckets to obtain the final sorted array.
CODE
#include <stdio.h>
#include <stdlib.h>
#define MAX 10 // Maximum number of elements in the array
#define BUCKETS 5 // Number of buckets
void bucketSort(float arr[], int n);
void insertionSort(float arr[], int n);
void printArray(float arr[], int n);
int main() {
float arr[MAX] = {0.42, 0.32, 0.33, 0.52, 0.37, 0.47, 0.51};
int n = 7; // Number of elements in the array
bucketSort(arr, n);
return 0;
}
void bucketSort(float arr[], int n) {
// Create empty buckets
float buckets[BUCKETS][MAX];
int bucketCount[BUCKETS] = {0}; // To keep track of the number of elements in each bucket
OUTPUT
Original Array:
0.45 0.32 0.36 0.67 0.37 0.47 0.49
Sorted Array:
0.32 0.36 0.37 0.45 0.47 0.49 0.67
PROGRAM NO: 3
AIM:-Write a program to implement Tower of Hanoi problem using Stack..
ALGORITHM
Initialize the Problem:
Let n be the number of disks.
There are three poles: Source (A), Auxiliary (B), and Destination (C).
Represent each pole as a stack.
Push Initial State to Stack:
Define a structure, say Move, that contains information about the source pole, destination pole, and the
number of disks.
Create an empty stack for moves, and push the initial move (i.e., move n disks from Source to
Destination using Auxiliary).
Iteratively Process Moves:
While there are moves in the stack:
o Pop the top move from the stack.
o Check the number of disks (num) for this move:
If num is 1:
Move the disk from the Source to Destination pole.
If num> 1:
Break down the move into three sub-moves (mimicking the recursive steps):
1. Push a move to transfer num - 1 disks from Auxiliary to Destination
using Source.
2. Push a move to transfer the single largest disk from Source to
Destination.
3. Push a move to transfer num - 1 disks from Source to Auxiliary using
Destination.
End of Algorithm:
Repeat the above steps until all disks have been moved from the Source pole to the Destination pole.
Print each move as disks are transferred to visualize the process.
CODE
#include <stdio.h>
#include <stdlib.h>
typedef struct Move {
int num; // Number of disks to move
char src; // Source pole
char dest; // Destination pole
char aux; // Auxiliary pole
} Move;
typedef struct Stack {
Move data[100];
int top;
} Stack;
void push(Stack *s, Move move) {
s->data[++(s->top)] = move;
}
Move pop(Stack *s) {
return s->data[(s->top)--];
}
int isEmpty(Stack *s) {
return s->top == -1;
}
void towerOfHanoi(int n, char src, char dest, char aux) {
Stack s;
s.top = -1;
while (!isEmpty(&s)) {
Move move = pop(&s);
if (move.num == 1) {
printf("Move disk 1 from %c to %c\n", move.src, move.dest);
} else {
// Push the steps in reverse order to simulate recursive calls in stack
Move step1 = { move.num - 1, move.aux, move.dest, move.src };
Move step2 = { 1, move.src, move.dest, move.aux };
Move step3 = { move.num - 1, move.src, move.aux, move.dest };
push(&s, step1); // Move num-1 disks from auxiliary to destination
push(&s, step2); // Move the largest disk from source to destination
push(&s, step3); // Move num-1 disks from source to auxiliary
}
}
}
int main() {
int n;
printf("Enter the number of disks: ");
scanf("%d", &n);
towerOfHanoi(n, 'A', 'C', 'B');
return 0;
}
OUTPUT