Assignment 15 To 24 Dsa
Assignment 15 To 24 Dsa
OUTPUT:
ASSIGNMENT 13
PROBLEM : Write a program in C to find the GCD of the numbers using recursion.
ALGORITHM:
1.Start
2. Input two positive integers, `num1` and `num2`.
3. Call the recursive function `gcd(a, b)`:
Base Case: If `b == 0`, return `a` (the GCD is found).
Recursive Case: If `b != 0`, call the function again with `gcd(b, a % b)`.
4. The recursive calls continue until `b` becomes 0.
5. Return the value of `a` as the GCD
6. Display the GCD result.
7. Stop
SOURCE CODE:
#include <stdio.h>
// Function to calculate the GCD using recursion
int gcd(int a, int b) {
if (b == 0) // Base case: if the second number is 0, return the first number
return a;
return gcd(b, a % b); // Recursive call: gcd(b, a % b)
}
int main() {
int num1, num2;
// Prompt the user to input two numbers
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
// Call the gcd function and display the result
printf("GCD of %d and %d is: %d\n", num1, num2, gcd(num1, num2));
return 0;
}
OUTPUT:
ASSIGNMENT 14
PROBLEM: Write a program in C to find the Fibonacci series using recursion give the size of the series
as user input.
ALGORITHM:
1. Start.
2. Input `n`, the size of the Fibonacci series, from the user.
3. Check for valid input:
- If `n <= 0`, display a message: "The size must be greater than 0" and terminate the program.
4. Define the recursive function `fibonacci(n)`:
- Base Case:
- If `n == 0`, return `0`.
- If `n == 1`, return `1`.
- Recursive Case:
- Return `fibonacci(n - 1) + fibonacci(n - 2)`.
5. Generate the Fibonacci series:
- Use a loop from `i = 0` to `i < n`:
- Call the `fibonacci(i)` function to compute the `i`-th Fibonacci number.
- Print the result.
6. End.
SOURCE CODE:
#include <stdio.h>
// Recursive function to calculate the nth Fibonacci number
int fibonacci(int n) {
if (n == 0)
return 0; // Base case: 0th Fibonacci number is 0
if (n == 1)
return 1; // Base case: 1st Fibonacci number is 1
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive call
}
int main() {
int n;
// Input the size of the Fibonacci series
printf("Enter the size of the Fibonacci series: ");
scanf("%d", &n);
if (n <= 0) {
printf("The size must be greater than 0.\n");
return 0;
}
// Display the Fibonacci series
printf("Fibonacci series up to %d terms:\n", n);
for (int i = 0; i < n; i++) {
printf("%d ", fibonacci(i)); // Call the recursive function
}
printf("\n");
return 0;
}
OUTPUT:
ASSIGNMENT 18
PROBLEM: Write a c program to show the operations of a circular queue implemented as an array.
ALGORITHM:
1. Initialization
1. Define constants:
- `MAX`: Maximum size of the circular queue.
2. Declare the variables:
- `queue[MAX]`: Array to store queue elements.
- `front` and `rear` are set to `-1` initially, representing an empty queue.
2. Enqueue Operation
1. Input the element to be inserted (`value`).
2. Check if the queue is full:
- If `(front == 0 && rear == MAX - 1)` OR `(front == rear + 1)`, display "Queue Overflow" and
terminate the operation.
3. If the queue is not full:
- If the queue is empty (`front == -1`):
- Set `front = 0` and `rear = 0`.
- Else if `rear == MAX - 1` (last position of the array), wrap around:
- Set `rear = 0`.
- Otherwise, increment `rear` by `1` (`rear = rear + 1`).
- Insert the element at `queue[rear]`.
4. Display a success message indicating the element was enqueued.
3. Dequeue Operation
1. Check if the queue is empty:
- If `front == -1`, display "Queue Underflow" and terminate the operation.
2. If the queue is not empty:
- Retrieve the element at `queue[front]` for display.
- If `front == rear` (only one element in the queue):
- Set `front = -1` and `rear = -1` (queue becomes empty).
- Else if `front == MAX - 1` (last position of the array), wrap around:
- Set `front = 0`.
- Otherwise, increment `front` by `1` (`front = front + 1`).
3. Display a success message indicating the element that was dequeued
4. Display Operation
1. Check if the queue is empty:
- If `front == -1`, display "Queue is empty."
2. If the queue is not empty:
- If `rear >= front` (no wrapping):
- Traverse from `front` to `rear` and display the elements.
- If `rear < front` (wrapping occurred):
- Traverse from `front` to `MAX - 1` and display the elements.
- Traverse from `0` to `rear` and display the elements.
5. Main Program (Menu-Driven)
1. Repeat the following steps until the user chooses to exit:
- Display the menu:
1. Enqueue
2. Dequeue
3. Display
4. Exit
- Input the user's choice.
- Perform the respective operation based on the choice:
- Call `enqueue()` for inserting an element.
- Call `dequeue()` for deleting an element.
- Call `display()` for showing the queue contents.
- Exit if the user chooses option 4.
- If an invalid choice is entered, display an error message.
SOURCE CODE:
#include <stdio.h>
#define MAX 5 // Define the maximum size of the circular queue
int queue[MAX];
int front = -1, rear = -1;
// Function to check if the queue is full
int isFull() {
return (front == 0 && rear == MAX - 1) || (front == rear + 1);
}
// Function to check if the queue is empty
int isEmpty() {
return front == -1;
}
// Function to insert an element into the circular queue
void enqueue(int value) {
if (isFull()) {
printf("Queue Overflow! Cannot insert %d\n", value);
return;
}
if (isEmpty()) { // First element being inserted
front = rear = 0;
} else if (rear == MAX - 1 && front != 0) { // Wrap around
rear = 0;
} else { // Normal case
rear++;
}
queue[rear] = value;
printf("%d inserted into the queue\n", value);
}
// Function to delete an element from the circular queue
void dequeue() {
if (isEmpty()) {
printf("Queue Underflow! No elements to delete\n");
return;
}
printf("%d deleted from the queue\n", queue[front]);
if (front == rear) { // Queue becomes empty
front = rear = -1;
} else if (front == MAX - 1) { // Wrap around
front = 0;
} else { // Normal case
front++;
}
}
// Function to display the elements of the queue
void display() {
if (isEmpty()) {
printf("Queue is empty\n");
return;
}
printf("Queue elements: ");
if (rear >= front) { // No wrapping
for (int i = front; i <= rear; i++) {
printf("%d ", queue[i]);
}
} else { // Wrapping occurred
for (int i = front; i < MAX; i++) {
printf("%d ", queue[i]);
}
for (int i = 0; i <= rear; i++) {
printf("%d ", queue[i]);
}
}
printf("\n");
}
int main() {
int choice, value;
while (1) {
printf("\nCircular Queue Operations:\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to insert: ");
scanf("%d", &value);
enqueue(value);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
printf("Exiting...\n");
return 0;
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}
OUTPUT:
ASSIGNMENT 19
PROBLEM: Write a c program to show the operations of a circular queue implemented as a linked-list.
ALGORITHM:
1.Initialization:
1. Create a structure for a `Node` with two fields:
- `data`: Stores the element.
- `next`: Points to the next node.
2. Initialize two global pointers:
- `front` (initially set to `NULL`): Points to the front of the queue.
- `rear` (initially set to `NULL`): Points to the rear of the queue
2. Menu-Driven Interface:
1. Display the menu options to the user:
- Option 1: Enqueue an element.
- Option 2: Dequeue an element.
- Option 3: Display the queue elements.
- Option 4: Exit the program.
2. Use a `while` loop to continuously accept user choices until "Exit" is selected.
3.Enqueue Operation (Option 1):
- Input: The element to add (user-provided).
- Steps:
1. Allocate memory for a new node using `malloc`.
2. Assign the input value to the `data` field of the new node.
3. Check if the queue is empty (`front == NULL`):
- Set both `front` and `rear` to point to the new node.
- Point the `next` of the new node to itself (circular link).
4. If the queue is not empty:
- Set `rear->next` to point to the new node.
- Update `rear` to point to the new node.
- Set `rear->next` to `front` to maintain circularity.
5. Display a message confirming the value was enqueued.
4. Dequeue Operation (Option 2):
- Input: None (deletion is always from the front).
-Steps:
1. Check if the queue is empty (`front == NULL`):
- Print a message indicating that the queue is empty.
- Exit the operation.
2. If there is only one node in the queue (`front == rear`):
- Free the memory of the node.
- Set both `front` and `rear` to `NULL`.
3. If there are multiple nodes:
- Store the `front` node in a temporary pointer.
- Move the `front` pointer to the next node (`front->next`).
- Update `rear->next` to point to the new `front`.
- Free the memory of the removed node.
4. Display a message confirming the value that was dequeued.
5. Display Operation(Option 3):
- Input: None (simply traverses and displays elements).
- Steps:
1. Check if the queue is empty (`front == NULL`):
- Print a message indicating the queue is empty.
- Exit the operation.
2. If the queue is not empty:
- Start from the `front` node.
- Traverse through the queue using a `do-while` loop.
- Print the `data` of each node until you return to the `front`.
3. Display all the elements in the queue.
6. Exit Operation (Option 4):
- Input: User selects "Exit".
-Steps:
1. Print a message indicating the program is exiting.
2. Terminate the program using `exit(0)`.
Flow of the Program:
1. The program initializes the queue with `front = NULL` and `rear = NULL`.
2. The user selects an operation from the menu.
3. Depending on the selected operation, the corresponding function (`enqueue`, `dequeue`, or `display`)
is called.
4. The menu is displayed repeatedly until the user chooses to exit.
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
// Define the structure for a node in the circular queue
struct Node {
int data;
struct Node* next;
};
// Initialize front and rear pointers
struct Node* front = NULL;
struct Node* rear = NULL;
// Enqueue operation: Adds an element to the queue
void enqueue(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
return;
}
newNode->data = value;
newNode->next = NULL;
if (front == NULL) { // If the queue is empty
front = rear = newNode;
rear->next = front; // Point to itself to make it circular
} else {
rear->next = newNode;
rear = newNode;
rear->next = front; // Maintain circular link
}
printf("Enqueued: %d\n", value);
}
// Dequeue operation: Removes an element from the queue
void dequeue() {
if (front == NULL) { // If the queue is empty
printf("Queue is empty! Cannot dequeue.\n");
return;
}
struct Node* temp = front;
if (front == rear) { // If there's only one element
front = rear = NULL;
} else {
front = front->next;
rear->next = front; // Maintain circular link
}
printf("Dequeued: %d\n", temp->data);
free(temp);
}
// Display operation: Shows the elements in the queue
void display() {
if (front == NULL) { // If the queue is empty
printf("Queue is empty!\n");
return;
}
struct Node* temp = front;
printf("Queue elements: ");
do {
printf("%d ", temp->data);
temp = temp->next;
} while (temp != front);
printf("\n");
}
int main() {
int choice, value;
while (1) {
printf("\nCircular Queue Operations:\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the value to enqueue: ");
scanf("%d", &value);
enqueue(value);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
printf("Exiting...\n");
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}
OUTPUT:
ASSIGNMENT 20
PROBLEM: Write a C program to create and perform different operations on double ended queues
using linked list implementations.
ALGORITHM:
Double-Ended Queue Using Linked List**
1. Node Structure:
- Each node contains:
- `data`: The value to store.
- `prev`: A pointer to the previous node.
- `next`: A pointer to the next node.
2. Initialization:
- Initialize two global pointers:
- `front`: Points to the first node of the deque (initially `NULL`).
- `rear`: Points to the last node of the deque (initially `NULL`).
3. Insert at the Front:
- Input: The value to insert.
- Steps:
1. Create a new node and assign the value to its `data`.
2. Set `newNode->prev` to `NULL` and `newNode->next` to the current `front`.
3. If the deque is empty (`front == NULL`):
- Set both `front` and `rear` to the new node.
4. Otherwise:
- Set `front->prev` to `newNode`.
- Update `front` to `newNode`.
5. Display a message confirming the insertion.
OUTPUT:
ASSIGNMENT 17
PROBLEM: Write a C program to evaluate a postfix expression using a Stack.
ALGORITHM:
1. Initialize the Stack:
- Create an empty stack to store operands.
2. Iterate Through the Expression:
- Start reading the postfix expression character by character.
3. Check Each Character:
- If the character is a digit (operand):
- Push it onto the stack.
- If the character is an operator (+, -, *, /):
- Pop the top two elements from the stack.
- Perform the operation using the two popped elements:
- Let `operand2` be the first element popped.
- Let `operand1` be the second element popped.
- Apply the operation (`operand1 operator operand2`).
- Push the result of the operation back onto the stack.
4.Handle Invalid Input:
- If any character is not a valid digit or operator, terminate the program with an error message.
5. Continue Until End of Expression:
- Repeat the process for all characters in the postfix expression.
6. Final Result:
- After processing the entire expression, the result will be the only value left in the stack.
- Pop this value and output it as the final result.
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX 100
// Stack structure
typedef struct {
int data[MAX];
int top;
} Stack;
// Stack operations
void push(Stack *stack, int value) {
stack->data[++(stack->top)] = value;
}
int pop(Stack *stack) {
return stack->data[(stack->top)--];
}
// Function to evaluate postfix expression
int evaluatePostfix(char *expression) {
Stack stack;
stack.top = -1;
char *e = expression;
while (*e != '\0') {
if (isdigit(*e)) {
// Push the numeric value onto the stack
push(&stack, *e - '0');
} else {
// Pop two operands and apply the operator
int operand2 = pop(&stack);
int operand1 = pop(&stack);
switch (*e) {
case '+':
push(&stack, operand1 + operand2);
break;
case '-':
push(&stack, operand1 - operand2);
break;
case '*':
push(&stack, operand1 * operand2);
break;
case '/':
push(&stack, operand1 / operand2);
break;
default:
printf("Invalid operator: %c\n", *e);
exit(1);
}
}
e++;
}
return pop(&stack);
}
int main() {
char expression[MAX];
printf("Enter the postfix expression (e.g., 53+82-*): ");
fgets(expression, MAX, stdin);
expression[strcspn(expression, "\n")] = '\0'; // Remove newline character
int result = evaluatePostfix(expression);
printf("The result is: %d\n", result);
return 0;
}
OUTPUT:
ASSIGNMENT 15
PROBLEM: Write a C program to convert a infix expression into its postfix equivalent using a stack.
ALGORITHM:
Scan the symbols of the expression from left to right and for each symbol, do the following
Step 1:If symbol is an operand
Print that symbol onto the screen
Step 2:If symbol is a left paranthesis
Push it on the stack
Step 3:If symbol is a right paranthesis
Pop all the operators from the stack uopto the first left parenthesis and print them on the screen.
Discard the left and right parenthesis.
Step 4:If symbol is an operator
If the precedence of the operators in the stack are greater than or equal to the current operator then
pop the operators out of the stack and print them onto the screen and push the current operator
onto the stack .
Else
push the current operator onto the stack.
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX 100 // Maximum stack size
// Stack structure
char stack[MAX];
int top = -1;
// Function to push an element onto the stack
void push(char c) {
if (top == MAX - 1) {
printf("Stack Overflow\n");
} else {
stack[++top] = c;
}
}
// Function to pop an element from the stack
char pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
} else {
return stack[top--];
}
}
// Function to return the precedence of operators
int precedence(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
if (op == '^') return 3;
return 0;
}
// Function to check if a character is an operator
int is_operator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^';
}
// Function to convert infix to postfix
void infix_to_postfix(char* infix, char* postfix) {
int i = 0, j = 0;
char symbol, temp;
while ((symbol = infix[i++]) != '\0') {
if (isalnum(symbol)) { // Operand
postfix[j++] = symbol;
} else if (symbol == '(') { // Left parenthesis
push(symbol);
} else if (symbol == ')') { // Right parenthesis
while ((temp = pop()) != '(') {
postfix[j++] = temp;
}
} else if (is_operator(symbol)) { // Operator
while (top != -1 && precedence(stack[top]) >= precedence(symbol)) {
postfix[j++] = pop();
}
push(symbol);
}
}
// Pop all remaining operators from the stack
while (top != -1) {
postfix[j++] = pop();
}
postfix[j] = '\0'; // Null-terminate the postfix expression
}
// Main function
int main() {
char infix[MAX], postfix[MAX];
printf("Enter the infix expression: ");
scanf("%s", infix);
infix_to_postfix(infix, postfix);
printf("Postfix Expression: %s\n", postfix);
return 0;
}
OUTPUT:
ASSIGNMENT 21
PROBLEM: Write a C program to convert prefix expression to its equivalent postfix expression using
stack.
ALGORITHM:
1. Initialize a stack to store intermediate results.
2. Traverse the prefix expression from right to left (starting from the last character):
- If the current character is an operand (a letter or digit):
- Push the operand onto the stack.
- If the current character is an operator (`+`, `-`, `*`, `/`, etc.):
1. Pop the top two elements from the stack (these are the two operands for the operator).
2. Concatenate the two operands in the following order: `<operand1><operand2><operator>`.
3. Push the resulting expression back onto the stack.
3. After the traversal is complete, the stack will contain one element, which is the final postfix
expression.
4. Pop and return the final postfix expression from the stack.
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 100
// Stack structure
typedef struct Stack {
char items[MAX][MAX];
int top;
} Stack;
// Initialize stack
void initStack(Stack* stack) {
stack->top = -1;
}
OUTPUT:
ASSIGNMENT 22
PROBLEM:Write a C program to reverse the order of the elements in the stack using additional stack.
ALGORITHM:
1. Initialize Temporary Storage:
- Declare a temporary stack (`tempStack`) to hold reversed elements.
- Set the `top` pointer of `tempStack` to `-1`.
int main() {
int stack[MAX], size,i;
reverseStack(stack, size);
return 0;
}
OUTPUT:
ASSIGNMENT 24
PROBLEM: Write a C program to implement Merge Sort.Show the output for the best as well as worst
case.
ALGORITHM:
1. Start with Input:
- Accept an array of `n` elements from the user.
- Take the size of the array `n` and the elements as input.
2. Recursive Division:
- Call the `mergeSort` function with parameters: the array, the left index (`left = 0`), and the right
index (`right = n-1`).
- If `left < right`, find the middle index (`mid = left + (right - left) / 2`).
- Recursively call `mergeSort` for:
- The left half: from `left` to `mid`.
- The right half: from `mid + 1` to `right`.
3. Merge Sorted Halves:
- After both halves are sorted, call the `merge` function to combine them.
- The `merge` function performs the following:
- Create two temporary arrays to hold elements of the left and right halves.
- Compare elements of both temporary arrays and copy the smaller element back into the original
array.
- Copy any remaining elements from the temporary arrays into the original array.
4. Base Condition for Recursion:
- If `left >= right`, stop further division (the array segment contains a single element, which is
inherently sorted).
5. Output the Sorted Array:
- Once the recursive calls and merges are complete, the array is fully sorted.
- Print the sorted array.
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
// Function to merge two halves
void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
// Temporary arrays
int L[n1], R[n2];
// Copy data to temporary arrays
for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
// Merge temporary arrays back into the original array
i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
// Copy remaining elements of L[], if any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
// Copy remaining elements of R[], if any
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
// Function to implement Merge Sort
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
// Recursively sort the first and second halves
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
// Merge the sorted halves
merge(arr, left, mid, right);
}
}
// Function to print an array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int n;
WORST CASE
ASSIGNMENT 25
PROBLEM: Write a C program to implement Heap Sort. Show the output for the best and worst case.
ALGORITHM:
1. Input:
- Start with an array of `n` elements.
2. Build a Max Heap:
- Treat the array as a complete binary tree.
- For all non-leaf nodes, starting from the last non-leaf node (index `n/2 - 1`), perform the `heapify`
operation to ensure the subtree rooted at each node satisfies the max heap property.
- The max heap property ensures that every parent node is greater than or equal to its children.
3. Heapify Function:
- Compare the root node with its left and right children.
- If the left or right child is larger than the root, swap the root with the largest child.
- Recursively call `heapify` on the affected child node to restore the max heap property.
4. Sorting the Array:
- Swap the root of the max heap (largest element) with the last element of the array.
- Reduce the heap size by one (exclude the last element, which is now sorted).
- Perform the `heapify` operation on the root to restore the max heap property for the reduced heap.
- Repeat this process until all elements are sorted.
5. Output the Sorted Array:
SOURCE CODE:
#include <stdio.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
void heapify(int arr[], int n, int i) {
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // Left child
int right = 2 * i + 2; // Right child
// If the left child is larger than the root
if (left < n && arr[left] > arr[largest]) {
largest = left;
}
// If the right child is larger than the largest so far
if (right < n && arr[right] > arr[largest]) {
largest = right;
}
// If the largest is not the root
if (largest != i) {
swap(&arr[i], &arr[largest]);
// Recursively heapify the affected subtree
heapify(arr, n, largest);
}
}
void heapSort(int arr[], int n) {
// Build a max heap
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
// Extract elements from the heap one by one
for (int i = n - 1; i > 0; i--) {
// Move the current root to the end
swap(&arr[0], &arr[i]);
// Call heapify on the reduced heap
heapify(arr, i, 0);
}
}
OUTPUT:
BEST CASE
WORST CASE
ASSIGNMENT 26
PROBLEM: Write a C program to implement Radix Sort. Show the output for the best and worst case.
ALGORITHM:
1. Determine the Maximum Value:
Identify the largest number in the array to determine the maximum number of digits (`d`) in the array
elements.
2. Iterate Through Each Digit Place:
Start sorting the numbers based on the least significant digit (LSD), moving toward the most significant
digit (MSD). For each digit place:
- Initialize Buckets:
Create 10 buckets (or lists) for digits 0 through 9.
- Place Elements in Buckets:
Place each element in the bucket corresponding to the current digit.
- Collect from Buckets:
Collect the elements from the buckets in order (from 0 to 9) to form the updated array.
3. Repeat for Each Digit Place:
Repeat the process for all digit places, from LSD to MSD, until the array is fully sorted.
4. Output the Sorted Array:
After processing all digit places, the array is sorted.
SOURCE CODE:
#include <stdio.h>
int getMax(int arr[], int n) {
int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
void countingSort(int arr[], int n, int exp) {
int output[n];
int count[10] = {0};
// Count occurrences of each digit
for (int i = 0; i < n; i++) {
count[(arr[i] / exp) % 10]++;
}
// Update count[i] to store cumulative positions
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
// Build the output array
for (int i = n - 1; i >= 0; i--) {
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}
WORST CASE
ASSIGNMENT 23
PROBLEM STATEMENT: Write a C program to reverse the order of the elements in the stack using
additional Queue.
ALGORITHM:
Input:
- A stack `S` with `N` elements.
- An empty queue `Q`.
Steps:
1.Initialize an Empty Queue:
- Create an empty queue `Q`.
4.
Push Queue Elements Back into Stack:
- While the queue `Q` is not empty:
- Dequeue the front element from queue `Q`.
- Push the dequeued element back onto stack `S`.
5. Output:
- The stack `S` is now reversed.
Output:
- Stack `S` with its elements in reversed order.
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h
#define MAX 100
void reverseStack(int stack[], int *top, int queue[], int *front, int *rear) {
// Push all stack elements to the queue
while (*top != -1) {
int value = pop(stack, top);
enqueue(queue, rear, value);
}
int main() {
int stack[MAX], queue[MAX];
int top = -1, front = 0, rear = -1;
int size, element;
printf("Enter the number of elements in the stack: ");
scanf("%d", &size);
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &element);
push(stack, &top, element);
}
printf("Original Stack: ");
displayStack(stack, top);
reverseStack(stack, &top, queue, &front, &rear);
printf("Reversed Stack: ");
displayStack(stack, top);
return 0;
}
OUTPUT: