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

Lab Manual

The document contains various algorithms implemented in C for fundamental mathematical and data structure operations. It includes methods to find the smallest divisor of an integer, generate prime numbers, calculate the product of two integers using repeated sums, compute factorials, generate Fibonacci series, find maximum and minimum values using divide and conquer, and perform breadth-first search in a binary tree. Each algorithm is presented with both iterative and recursive implementations, showcasing different approaches to problem-solving in computer science.

Uploaded by

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

Lab Manual

The document contains various algorithms implemented in C for fundamental mathematical and data structure operations. It includes methods to find the smallest divisor of an integer, generate prime numbers, calculate the product of two integers using repeated sums, compute factorials, generate Fibonacci series, find maximum and minimum values using divide and conquer, and perform breadth-first search in a binary tree. Each algorithm is presented with both iterative and recursive implementations, showcasing different approaches to problem-solving in computer science.

Uploaded by

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

Analysis and Design of Algorithm(MCAXX13516) 20230203010018

1. Determine smallest divisor of an integer.


#include <stdio.h>
int main() {
int num;
// Input the number
printf("Enter a number: ");
scanf("%d", &num);
// Handle cases for numbers less than 2
if (num < 2) {
printf("Smallest divisor of %d is %d\n", num, num);
return 0;
}
// Find the smallest divisor
for (int i = 2; i <= num; i++) {
if (num % i == 0) {
printf("Smallest divisor of %d is %d\n", num, i);
break; // Exit loop once smallest divisor is found
}
}
return 0;
}

#include <stdio.h>
// Recursive function to find the smallest divisor
int findSmallestDivisor(int n, int divisor) {
// Base case: if divisor divides n, return the divisor
if (n % divisor == 0) {
return divisor;
}
// Recursive case: check the next divisor
return findSmallestDivisor(n, divisor + 1);
}
int main() {
int n;
// Input the integer
printf("Enter a positive integer: ");
scanf("%d", &n);
// Edge case: smallest divisor of 1 is 1
if (n == 1) {
printf("The smallest divisor of 1 is 1.\n");
} else {
// Call the recursive function starting with divisor 2
int smallestDivisor = findSmallestDivisor(n, 2);
printf("The smallest divisor of %d is %d.\n", n, smallestDivisor);
}
return 0;
}

Gyanmanjari College of Computer Application 1|Page


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

2. For a given value of n, generate prime numbers <= n (more than one algorithms
are possible)
#include<stdio.h>
void main(){
int i, num, n, count;
printf("Enter the range: ");
scanf("%d", &n);
printf("The prime numbers in between the range 1 to %d:",n);
for(num = 1;num<=n;num++){
count = 0;
for(i=2;i<=num/2;i++){
if(num%i==0){
count++;
break;
}
}
if(count==0 && num!= 1)
printf("%d ",num);
}
}

#include <stdio.h>
#include <stdbool.h>
// Helper function to check if a number is prime (Recursive)
bool is_prime_recursive(int num, int divisor) {
if (num < 2) return false;
if (divisor * divisor > num) return true;
if (num % divisor == 0) return false;
return is_prime_recursive(num, divisor + 1);
}
// Function to print primes using recursion
void generate_primes_recursive(int n, int current) {
if (current > n) return;
if (is_prime_recursive(current, 2)) {
printf("%d ", current);
}
generate_primes_recursive(n, current + 1);
}
// Main function
int main() {
int n;
printf("Enter the value of n: ");
scanf("%d", &n);
printf("Prime numbers <= %d (Recursive): ", n);
generate_primes_recursive(n, 2);
return 0;
}

Gyanmanjari College of Computer Application 2|Page


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

3. Determine product of 2 integers (a * b) as repeated sums. Iterative and recursive algorithms are
possible.
#include <stdio.h>
int main() {
int a, b, result = 0;
// Input two integers
printf("Enter two integers:\n");
scanf("%d %d", &a, &b);
// Iterative approach: Calculate product using repeated sums
for (int i = 0; i < b; i++) {
result += a; // Add `a` repeatedly `b` times
}
printf("Product of %d and %d using iterative method is: %d\n", a, b, result);
return 0;
}

#include <stdio.h>
int main() {
int a, b;
// Input two integers
printf("Enter two integers:\n");
scanf("%d %d", &a, &b);
// Recursive function to calculate product
int product(int x, int y) {
// Base case
if (y == 0) {
return 0; // Product is 0 if any one number is 0
}
// Recursive case: add x and call recursively with (x, y - 1)
return x + product(x, y - 1);
}
// Calculate product using recursive function
int result = product(a, b);
printf("Product of %d and %d using recursive method is: %d\n", a, b, result);
return 0;
}

Gyanmanjari College of Computer Application 3|Page


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

4. Find Factorial of n. Iterative and recursive algorithms are possible.


#include <stdio.h>
int main() {
int n;
long factorial = 1; // Use long to handle large results
// Input an integer
printf("Enter a positive integer: ");
scanf("%d", &n);
// Iterative approach: Calculate factorial
for (int i = 1; i <= n; i++) {
factorial *= i; // Multiply each integer from 1 to n
}
printf("Factorial of %d using iterative method is: %ld\n", n, factorial);
return 0;
}

#include <stdio.h>
int main() {
int n;
// Input an integer
printf("Enter a positive integer: ");
scanf("%d", &n);
// Recursive function to calculate factorial
long factorial(int x) {
// Base case
if (x == 0 || x == 1) {
return 1; // Factorial of 0 or 1 is 1
}
// Recursive case: x * factorial of (x - 1)
return x * factorial(x - 1);
}
// Calculate factorial using recursive function
long result = factorial(n);
printf("Factorial of %d using recursive method is: %ld\n", n, result);
return 0;
}

Gyanmanjari College of Computer Application 4|Page


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

5. Generate Fibonacci series up to n terms Iterative and recursive algorithms are possible.
#include <stdio.h>
int main() {
int n;
// Input number of terms
printf("Enter the number of terms for Fibonacci series: ");
scanf("%d", &n);
// Declare variables for Fibonacci
int a = 0, b = 1, next;
// Print Fibonacci series
printf("Fibonacci series up to %d terms: \n", n);
for (int i = 1; i <= n; i++) {
printf("%d ", a);
next = a + b; // Calculate next term
a = b; // Update a
b = next; // Update b
}
printf("\n");
return 0;
}

#include <stdio.h>
int main() {
int n;
// Input number of terms
printf("Enter the number of terms for Fibonacci series: ");
scanf("%d", &n);
// Recursive function to print Fibonacci series
void fibo(int x, int a, int b) {
// Base case
if (x == 0) {
return; // No more terms to print
}
// Print the current Fibonacci term
printf("%d ", a);
// Recursive call with updated values
fibo(x - 1, b, a + b);
}
// Print Fibonacci series using recursive function
printf("Fibonacci series up to %d terms: \n", n);
fibo(n, 0, 1); // Start with 0 and 1
printf("\n");
return 0;
}

Gyanmanjari College of Computer Application 5|Page


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

6. Program for finding maximum and minimum number using Divide and conquer.
#include <stdio.h>
void findMinMax(int arr[], int low, int high, int *min, int *max) {
if (low == high) {
if (arr[low] > *max) *max = arr[low];
if (arr[low] < *min) *min = arr[low];
return;
}
if (high == low + 1) {
if (arr[low] > arr[high]) {
if (arr[low] > *max) *max = arr[low];
if (arr[high] < *min) *min = arr[high];
} else {
if (arr[high] > *max) *max = arr[high];
if (arr[low] < *min) *min = arr[low];
}
return;
}
int mid = (low + high) / 2;
findMinMax(arr, low, mid, min, max);
findMinMax(arr, mid + 1, high, min, max);
}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements:\n");
for(int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int min = arr[0];
int max = arr[0];
findMinMax(arr, 0, n - 1, &min, &max);
printf("Minimum element is %d\n", min);
printf("Maximum element is %d\n", max);
return 0;
}

#include <stdio.h>
// Function to find the minimum and maximum using divide and conquer
void findMinMax(int arr[], int low, int high, int *min, int *max) {
int mid;
int min1, max1; // Variables to store the results of the other half
// Base case: If there's only one element
if (low == high) {
*min = *max = arr[low];
return;
}
// If there are two elements, compare them directly
if (high == low + 1) {
if (arr[low] > arr[high]) {
*max = arr[low];
*min = arr[high];

Gyanmanjari College of Computer Application 6|Page


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

} else {
*max = arr[high];
*min = arr[low];
}
return;
}
// Recursively divide the array into two halves
mid = (low + high) / 2;
findMinMax(arr, low, mid, min, max); // Find min, max for left half
findMinMax(arr, mid + 1, high, &min1, &max1); // Find min, max for right half
// Compare the results of both halves
if (*min > min1) *min = min1;
if (*max < max1) *max = max1;
}
int main() {
int arr[] = {12, 3, 5, 7, 19, 23, 8, 10};
int n = sizeof(arr) / sizeof(arr[0]);
int min, max;
// Call the recursive function
findMinMax(arr, 0, n - 1, &min, &max);
// Print the result
printf("Minimum element: %d\n", min);
printf("Maximum element: %d\n", max);
return 0;
}

Gyanmanjari College of Computer Application 7|Page


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

7. Breadth First Search (BFS) in a binary tree.


#include <stdio.h>
#include <stdlib.h>
// Node structure
struct Node {
int data;
struct Node* left;
struct Node* right;
};

// Create a new node


struct Node* newNode(int data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}

// Print level order


void printLevelOrder(struct Node* root) {
if (root == NULL)
return;

struct Node* queue[100]; // Simple array-based queue


int front = 0, rear = 0;
queue[rear++] = root;

while (front < rear) {


struct Node* node = queue[front++];
printf("%d ", node->data);
if (node->left != NULL)
queue[rear++] = node->left;
if (node->right != NULL)
queue[rear++] = node->right;
}
}

int main() {
int n, data;

printf("Enter the number of nodes: ");


scanf("%d", &n);

struct Node* nodes[n];

printf("Enter node values:\n");


for (int i = 0; i < n; i++) {
scanf("%d", &data);
nodes[i] = newNode(data);
}

Gyanmanjari College of Computer Application 8|Page


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

struct Node* root = nodes[0]; // Let's assume the first node as root
for (int i = 0; i < n; i++) {
int leftIndex = 2 * i + 1;
int rightIndex = 2 * i + 2;
if (leftIndex < n) {
nodes[i]->left = nodes[leftIndex];
}
if (rightIndex < n) {
nodes[i]->right = nodes[rightIndex];
}
}
printf("Level Order traversal of binary tree is: ");
printLevelOrder(root);
return 0;
}

#include <stdio.h>
#include <stdlib.h>
// Structure for a node in the binary tree
struct Node {
int data;
struct Node *left, *right;
};
// Function to create a new node
struct Node* newNode(int data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return node;
}
// Function to find the height of the tree
int height(struct Node* root) {
if (root == NULL)
return 0;
else {
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return (leftHeight > rightHeight) ? (leftHeight + 1) : (rightHeight + 1);
}
}
// Function to print all nodes at a given level
void printCurrentLevel(struct Node* root, int level) {
if (root == NULL)
return;
if (level == 1)
printf("%d ", root->data);
else if (level > 1) {
printCurrentLevel(root->left, level - 1);
printCurrentLevel(root->right, level - 1);
}
}

// Function to perform BFS (Level Order Traversal) using recursion


void BFS(struct Node* root) {

Gyanmanjari College of Computer Application 9|Page


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

int h = height(root);
for (int i = 1; i <= h; i++) {
printCurrentLevel(root, i);
}
}
// Function to insert nodes in a binary tree
struct Node* insertNode() {
int data;
printf("Enter data (-1 for no node): ");
scanf("%d", &data);
if (data == -1) {
return NULL; // No node to insert
}
struct Node* newNodePtr = newNode(data); // Create a new node
printf("Enter left child of %d:\n", data);
newNodePtr->left = insertNode(); // Recursively insert the left child
printf("Enter right child of %d:\n", data);
newNodePtr->right = insertNode(); // Recursively insert the right child
return newNodePtr;
}
int main() {
printf("Create the binary tree:\n");
struct Node* root = insertNode(); // Create binary tree from user input
printf("\nBreadth-First Search (Level Order Traversal) of binary tree is: \n");
BFS(root); // Perform BFS
return 0;
}

Gyanmanjari College of Computer Application 10 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

8. Depth First Search (DFS) in a binary tree.


#include <stdio.h>
#include <stdlib.h>
// Node structure
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Create a new node
struct Node* newNode(int data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
// In-order DFS traversal
void inOrder(struct Node* node) {
if (node == NULL)
return;
inOrder(node->left);
printf("%d ", node->data);
inOrder(node->right);
}
int main() {
int n, data;
printf("Enter the number of nodes: ");
scanf("%d", &n);
struct Node* nodes[n];
printf("Enter node values:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &data);
nodes[i] = newNode(data);
}
struct Node* root = nodes[0]; // Assuming the first node as root
for (int i = 0; i < n; i++) {
int leftIndex = 2 * i + 1;
int rightIndex = 2 * i + 2;
if (leftIndex < n) { nodes[i]->left = nodes[leftIndex]; }
if (rightIndex < n) { nodes[i]->right = nodes[rightIndex]; }
}
printf("In-order traversal of binary tree is: ");
inOrder(root);
return 0;
}

#include <stdio.h>
#include <stdlib.h>
// Structure for a node in the binary tree
struct Node {
int data;
struct Node *left, *right;
};

Gyanmanjari College of Computer Application 11 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

// Function to create a new node


struct Node* newNode(int data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return node;
}
// Function to perform in-order DFS traversal (recursive)
void DFS_InOrder(struct Node* root) {
if (root == NULL)
return;
// Traverse the left subtree first (DFS on left subtree)
DFS_InOrder(root->left);
// Visit the root (current node)
printf("%d ", root->data);
// Traverse the right subtree (DFS on right subtree)
DFS_InOrder(root->right);
}
// Function to insert nodes in a binary tree
struct Node* insertNode() {
int data;
printf("Enter data (-1 for no node): ");
scanf("%d", &data);
if (data == -1) {
return NULL; // No node to insert
}
struct Node* newNodePtr = newNode(data); // Create a new node
printf("Enter left child of %d:\n", data);
newNodePtr->left = insertNode(); // Recursively insert the left child
printf("Enter right child of %d:\n", data);
newNodePtr->right = insertNode(); // Recursively insert the right child
return newNodePtr;
}
int main() {
printf("Create the binary tree:\n");
struct Node* root = insertNode(); // Create binary tree from user input
printf("\nDepth First Search (In-Order Traversal) of the binary tree is: \n");
DFS_InOrder(root); // Perform DFS using in-order traversal
printf("\n");
return 0;
}

Gyanmanjari College of Computer Application 12 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

9. Binary Search of an ordered array. Iterative and Recursive algorithms are possible.
#include <stdio.h>
int main() {
int n, target;
printf("Enter number of elements:");
scanf("%d", &n);
int arr[n];
printf("Enter %d sorted elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter target element to search:");
scanf("%d", &target);

int low = 0;
int high = n - 1;
int foundIndex = -1; // Variable to store the result
// Perform binary search
while (low <= high) {
int mid = low + (high - low) / 2; // Prevent potential overflow
// Check if target is present at mid
if (arr[mid] == target) {
foundIndex = mid; // Target found
break; // Exit the loop as we found the target
}
// If target is greater, ignore the left half
else if (arr[mid] < target) {
low = mid + 1;
}
// If target is smaller, ignore the right half
else {
high = mid - 1;
}
}
// Output result
if (foundIndex != -1) {
printf("Element found at index: %d\n", foundIndex);
} else {
printf("Element not found\n");
}
return 0;
}

#include <stdio.h>
// Function to perform recursive binary search
int binarySearchRecursive(int arr[], int low, int high, int target) {
// Base case: If the search space is empty
if (low > high) {
return -1; // Target not found
}
int mid = low + (high - low) / 2; // Prevent potential overflow
// Check if target is present at mid
if (arr[mid] == target) {
return mid; // Target found

Gyanmanjari College of Computer Application 13 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

}
// If target is smaller than mid, search the left half
if (arr[mid] > target) {
return binarySearchRecursive(arr, low, mid - 1, target);
}
// If target is larger than mid, search the right half
else {
return binarySearchRecursive(arr, mid + 1, high, target);
}
}
int main() {
int n, target;
// Input number of elements
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
// Input elements (assuming array is sorted)
printf("Enter %d sorted elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Input target element to search
printf("Enter target element to search:");
scanf("%d", &target);
// Perform binary search
int result = binarySearchRecursive(arr, 0, n - 1, target);
if (result != -1) {
printf("Element found at index:%d\n", result);
} else {
printf("Element not found\n");
}
return 0;
}

Gyanmanjari College of Computer Application 14 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

10. Sort a given sequence of numbers using Bubble Sort Algorithm.


#include <stdio.h>
int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);

int arr[n];
printf("Enter the elements:\n");

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


scanf("%d", &arr[i]);
}

for (int i = 0; i < n-1; i++) {


for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

printf("Sorted array: \n");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}

#include <stdio.h>
// Function to perform one pass of bubble sort
void bubbleSortRecursive(int arr[], int n) {
// Base case: If there is only one element, no need to sort
if (n == 1) {
return;
}
// Perform one pass of bubble sort
for (int i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1]) {
// Swap arr[i] and arr[i + 1] if they are in the wrong order
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
// Recursively call the function for the remaining unsorted part of the array
bubbleSortRecursive(arr, n - 1);
}
int main() {
int n;
// Input number of elements

Gyanmanjari College of Computer Application 15 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

printf("Enter number of elements: ");


scanf("%d", &n);
int arr[n];
// Input elements
printf("Enter %d elements: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Perform bubble sort
bubbleSortRecursive(arr, n);
// Output the sorted array
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}

Gyanmanjari College of Computer Application 16 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

11. Sort a given sequence of numbers using Merge Sort Algorithm.


#include <stdio.h>

int main() {
// Static array of numbers
int arr[] = {38, 27, 43, 3, 9, 82, 10};
int n = sizeof(arr)
// Merge function to merge two halves
void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1; // Size of the left half
int n2 = right - mid; // Size of the right half
// Create temporary arrays
int L[n1], R[n2];
// Copy data to temporary arrays L[] and R[]
for (i = 0; i < n1; i++) {
L[i] = arr[left + i];
}
for (j = 0; j < n2; j++) {
R[j] = arr[mid + 1 + j];
}
// Merge the temporary arrays back into arr[left..right]
i = 0; // Initial index of the first sub-array
j = 0; // Initial index of the second sub-array
k = left; // Initial index of merged sub-array
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++;
}
}

// Merge Sort function


void mergeSort(int arr[], int left, int right) {
if (left < right) {
// Find the middle point

Gyanmanjari College of Computer Application 17 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

int mid = left + (right - left) / 2;


// Sort first and second halves
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
// Merge the sorted halves
merge(arr, left, mid, right);
}
}
// Call the merge sort function
mergeSort(arr, 0, n - 1);
// Print sorted array
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}

#include <stdio.h>

// Merge function to merge two halves


void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1; // Size of the left half
int n2 = right - mid; // Size of the right half

// Create temporary arrays


int L[n1], R[n2];

// Copy data to temporary arrays L[] and R[]


for (i = 0; i < n1; i++) {
L[i] = arr[left + i];
}
for (j = 0; j < n2; j++) {
R[j] = arr[mid + 1 + j];
}

// Merge the temporary arrays back into arr[left..right]


i = 0; // Initial index of the first sub-array
j = 0; // Initial index of the second sub-array
k = left; // Initial index of merged sub-array
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 any

Gyanmanjari College of Computer Application 18 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

while (i < n1) {


arr[k] = L[i];
i++;
k++;
}

// Copy the remaining elements of R[], if any


while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

// Iterative Merge Sort function


void mergeSortIterative(int arr[], int n) {
int curr_size; // For current size of sub-arrays to be merged
int left_start; // For picking the starting index of sub-arrays

// Merge sub-arrays in bottom-up manner


for (curr_size = 1; curr_size <= n-1; curr_size = 2*curr_size) {
for (left_start = 0; left_start < n-1; left_start += 2*curr_size) {
int mid = left_start + curr_size - 1;
int right_end = (left_start + 2*curr_size - 1 < n-1) ? (left_start + 2*curr_size - 1) : (n-1);

// Merge sub-arrays arr[left_start...mid] and arr[mid+1...right_end]


merge(arr, left_start, mid, right_end);
}
}
}

int main() {
// Static array of numbers
int arr[] = {38, 27, 43, 3, 9, 82, 10};
int n = sizeof(arr) / sizeof(arr[0]);

// Call the iterative merge sort function


mergeSortIterative(arr, n);

// Print sorted array


printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

Gyanmanjari College of Computer Application 19 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

12. Solution of Rod-cutting problem using Dynamic Programming algorithm.


#include <stdio.h>
// Iterative function to find maximum revenue and keep track of cuts
void rodCuttingIterative(int prices[], int length, int *maxRevenue, int cuts[]) {
int revenue[length + 1]; // Array to store maximum revenue for each length
revenue[0] = 0; // Base case: length 0
// Calculate maximum revenue for each length
for (int j = 1; j <= length; j++) {
int maxRev = 0;
cuts[j] = 0; // Reset cut for current length
for (int i = 1; i <= j; i++) {
// Compare and update max revenue
int currentRevenue = prices[i] + revenue[j - i];
if (currentRevenue > maxRev) {
maxRev = currentRevenue;
cuts[j] = i; // Record the cut length
}
}
revenue[j] = maxRev; // Store the maximum revenue for length j
}
*maxRevenue = revenue[length]; // Return maximum revenue for full length
}
int main() {
int n;
// Input length of the rod
printf("Enter the length of the rod: ");
scanf("%d", &n);
// Input prices for each length
int prices[n + 1]; // prices[0] is unused
int cuts[n + 1]; // Array to store cuts
printf("Enter the prices for lengths 1 to %d:\n", n);
for (int i = 1; i <= n; i++) {
scanf("%d", &prices[i]);
}
int maxRevenue;
rodCuttingIterative(prices, n, &maxRevenue, cuts);
printf("Maximum revenue (iterative): %d\n", maxRevenue);
// Print the lengths of the cuts to achieve the maximum revenue
printf("Cuts to achieve maximum revenue:\n");
while (n > 0) {
printf("Cut: %d\n", cuts[n]);
n -= cuts[n]; // Reduce the length by the cut length
}
return 0;
}

#include <stdio.h>
// Recursive function to find maximum revenue and print lengths
void rodCuttingRecursive(int prices[], int length, int *maxRevenue) {
// Base case: if length is 0, no revenue can be obtained
if (length <= 0) {
return;
}
int localMax = 0;

Gyanmanjari College of Computer Application 20 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

int bestCut = 0;
// Try cutting the rod at different lengths
for (int i = 1; i <= length; i++) {
if (i <= length) {
// Compare and update max revenue
int currentRevenue = prices[i] + *maxRevenue;
if (currentRevenue > localMax) {
localMax = currentRevenue;
bestCut = i;
}
}
}
*maxRevenue = localMax; // Update maximum revenue
// Print the best cut
if (bestCut > 0) {
printf("Cut: %d\n", bestCut);
rodCuttingRecursive(prices, length - bestCut, maxRevenue);
}
}
int main() {
int n;
// Input length of the rod
printf("Enter the length of the rod: ");
scanf("%d", &n);
// Input prices for each length
int prices[n + 1]; // prices[0] is unused
printf("Enter the prices for lengths 1 to %d:\n", n);
for (int i = 1; i <= n; i++) {
scanf("%d", &prices[i]);
}
int maxRevenue = 0;
rodCuttingRecursive(prices, n, &maxRevenue);
printf("Maximum revenue (recursive): %d\n", maxRevenue);
return 0;
}

Gyanmanjari College of Computer Application 21 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

13. Prim's algorithm to find minimum cost tree (shortest path in a tree).
#include <stdio.h>
#include <limits.h>
#define V 5 // Number of vertices in the graph
// Function to find the vertex with the minimum key value
int minKey(int key[], int mstSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++) {
if (mstSet[v] == 0 && key[v] < min) {
min = key[v];
min_index = v;
}
}
return min_index;
}
// Function to implement Prim's algorithm
void primMST(int graph[V][V]) {
int parent[V]; // Array to store the constructed MST
int key[V]; // Key values to pick minimum weight edge in cut
int mstSet[V]; // To represent the set of vertices included in MST
// Initialize all keys as INFINITE
for (int i = 0; i < V; i++) {
key[i] = INT_MAX;
mstSet[i] = 0; // Not included in MST yet
}
// Always include the first vertex in MST
key[0] = 0; // Make key 0 so that this vertex is picked as the first vertex
parent[0] = -1; // First node is always the root of the MST
// The MST will have V vertices
for (int count = 0; count < V - 1; count++) {
// Pick the minimum key vertex from the set of vertices not yet included in MST
int u = minKey(key, mstSet);
// Add the picked vertex to the MST Set
mstSet[u] = 1;
// Update the key value and parent index of the adjacent vertices
for (int v = 0; v < V; v++) {
// Update key only if graph[u][v] is smaller than key[v]
if (graph[u][v] && mstSet[v] == 0 && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
// Print the constructed MST
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++) {
printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
}
}
int main() {
// Create the graph as an adjacency matrix
int graph[V][V] = {
{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},

Gyanmanjari College of Computer Application 22 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}
};
primMST(graph);
return 0;
}

#include <stdio.h>
#include <limits.h>
#define V 5 // Number of vertices in the graph
// Function to find the vertex with the minimum key value
int minKey(int key[], int mstSet[]) {
int min = INT_MAX, min_index = -1; // Initialize min_index to -1
for (int v = 0; v < V; v++) {
if (mstSet[v] == 0 && key[v] < min) {
min = key[v];
min_index = v;
}
}
return min_index;
}
// Recursive function to add edges to the MST
void addEdgeToMST(int graph[V][V], int key[], int mstSet[], int parent[], int count) {
// Base case: when we have V-1 edges
if (count == V - 1) {
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++) {
printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
}
return;
}
// Pick the minimum key vertex from the set of vertices not yet included in MST
int u = minKey(key, mstSet);
mstSet[u] = 1; // Add the picked vertex to the MST set
// Update the key value and parent index of the adjacent vertices
for (int v = 0; v < V; v++) {
if (graph[u][v] && mstSet[v] == 0 && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
// Recursive call for the next edge
addEdgeToMST(graph, key, mstSet, parent, count + 1);
}
// Function to implement Prim's algorithm
void primMST(int graph[V][V]) {
int parent[V]; // Array to store the constructed MST
int key[V]; // Key values to pick minimum weight edge in cut
int mstSet[V]; // To represent the set of vertices included in MST
// Initialize all keys as INFINITE
for (int i = 0; i < V; i++) {
key[i] = INT_MAX;
mstSet[i] = 0; // Not included in MST yet

Gyanmanjari College of Computer Application 23 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

}
// Always include the first vertex in MST
key[0] = 0; // Make key 0 so that this vertex is picked as the first vertex
parent[0] = -1; // First node is always the root of the MST
// Start the recursive edge addition
addEdgeToMST(graph, key, mstSet, parent, 0);
}
int main() {
// Create the graph as an adjacency matrix
int graph[V][V] = {
{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}
};
primMST(graph);
return 0;
}

Gyanmanjari College of Computer Application 24 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

14. Kruskal's algorithm to find minimum cost tree (shortest path in a tree).

#include <stdio.h>
#include <stdlib.h>
#define MAX 100
// Structure to represent an edge
typedef struct {
int u, v, weight;
} Edge;
// Function to compare edges based on weight
int compare(const void *a, const void *b) {
return ((Edge *)a)->weight - ((Edge *)b)->weight;
}
// Find function using path compression
int find(int parent[], int i) {
if (parent[i] != i)
parent[i] = find(parent, parent[i]);
return parent[i];
}
// Union function
void unionSets(int parent[], int rank[], int x, int y) {
if (rank[x] > rank[y]) {
parent[y] = x;
} else if (rank[x] < rank[y]) {
parent[x] = y;
} else {
parent[y] = x;
rank[x]++;
}
}
// Kruskal's algorithm to find the MST (Iterative)
void kruskalIterative(Edge edges[], int numEdges, int numVertices) {
qsort(edges, numEdges, sizeof(edges[0]), compare);
int parent[MAX], rank[MAX];
for (int i = 0; i < numVertices; i++) {
parent[i] = i;
rank[i] = 0;
}
printf("Edges in the Minimum Spanning Tree:\n");
for (int i = 0; i < numEdges; i++) {
int x = find(parent, edges[i].u);
int y = find(parent, edges[i].v);
if (x != y) {
printf("%d - %d: %d\n", edges[i].u, edges[i].v, edges[i].weight);
unionSets(parent, rank, x, y);
}
}
}
int main() {
Edge edges[] = {
{0, 1, 10},
{0, 2, 6},
{0, 3, 5},
{1, 3, 15},

Gyanmanjari College of Computer Application 25 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

{2, 3, 4}
};
int numEdges = sizeof(edges) / sizeof(edges[0]);
int numVertices = 4;
kruskalIterative(edges, numEdges, numVertices);
return 0;
}

#include <stdio.h>
#include <stdlib.h>
#define MAX 100
// Structure to represent an edge
typedef struct {
int u, v, weight;
} Edge;

// Function to compare edges based on weight


int compare(const void *a, const void *b) {
return ((Edge *)a)->weight - ((Edge *)b)->weight;
}
// Find function using path compression
int find(int parent[], int i) {
if (parent[i] != i)
parent[i] = find(parent, parent[i]);
return parent[i];
}
// Union function
void unionSets(int parent[], int rank[], int x, int y) {
if (rank[x] > rank[y]) {
parent[y] = x;
} else if (rank[x] < rank[y]) {
parent[x] = y;
} else {
parent[y] = x;
rank[x]++;
}
}
// Recursive function to implement Kruskal's algorithm
void kruskalRecursive(Edge edges[], int numEdges, int numVertices, int index, int parent[], int rank[]) {
if (index >= numEdges) return; // Base case: all edges processed
int x = find(parent, edges[index].u);
int y = find(parent, edges[index].v);
// If including this edge doesn't cause a cycle
if (x != y) {
printf("%d - %d: %d\n", edges[index].u, edges[index].v, edges[index].weight);
unionSets(parent, rank, x, y);
}
// Recursive call for the next edge
kruskalRecursive(edges, numEdges, numVertices, index + 1, parent, rank);
}

// Wrapper for the recursive function


void kruskalRecursiveWrapper(Edge edges[], int numEdges, int numVertices) {
qsort(edges, numEdges, sizeof(edges[0]), compare);

Gyanmanjari College of Computer Application 26 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

int parent[MAX], rank[MAX];


for (int i = 0; i < numVertices; i++) {
parent[i] = i;
rank[i] = 0;
}
printf("Edges in the Minimum Spanning Tree:\n");
kruskalRecursive(edges, numEdges, numVertices, 0, parent, rank);
}
int main() {
Edge edges[] = {
{0, 1, 10},
{0, 2, 6},
{0, 3, 5},
{1, 3, 15},
{2, 3, 4}
};
int numEdges = sizeof(edges) / sizeof(edges[0]);
int numVertices = 4;
kruskalRecursiveWrapper(edges, numEdges, numVertices);
return 0;
}

Gyanmanjari College of Computer Application 27 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

15. Implement Bellman-Ford Single Source Shortest Path Algorithm.


#include <stdio.h>
#include <limits.h>
#define V 5 // Number of vertices
#define E 8 // Number of edges
// Structure to represent an edge
typedef struct {
int u, v, weight;
} Edge;
// Function to implement Bellman-Ford algorithm (Iterative)
void bellmanFordIterative(Edge edges[], int source) {
int distance[V];
// Step 1: Initialize distances from source to all other vertices as INFINITE
for (int i = 0; i < V; i++) {
distance[i] = INT_MAX;
}
distance[source] = 0; // Distance from source to itself is always 0
// Step 2: Relax all edges |V| - 1 times
for (int i = 1; i < V; i++) {
for (int j = 0; j < E; j++) {
if (distance[edges[j].u] != INT_MAX &&
distance[edges[j].u] + edges[j].weight < distance[edges[j].v]) {
distance[edges[j].v] = distance[edges[j].u] + edges[j].weight;
}
}
}
// Step 3: Print the shortest distances
printf("Vertex Distance from Source:\n");
for (int i = 0; i < V; i++) {
printf("%d \t\t %d\n", i, distance[i]);
}
}
int main() {
// Define edges of the graph
Edge edges[E] = {
{0, 1, -1},
{0, 2, 4},
{1, 2, 3},
{1, 3, 2},
{1, 4, 2},
{3, 2, 5},
{3, 1, 1},
{4, 3, -3}
};
int source = 0; // Starting vertex
bellmanFordIterative(edges, source);
return 0;
}

#include <stdio.h>
#include <limits.h>
#define V 5 // Number of vertices
#define E 8 // Number of edges
// Structure to represent an edge

Gyanmanjari College of Computer Application 28 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

typedef struct {
int u, v, weight;
} Edge;
// Recursive function to relax edges
void relaxEdges(Edge edges[], int distance[], int edgesCount, int iterations) {
if (iterations <= 0) return; // Base case
for (int j = 0; j < edgesCount; j++) {
if (distance[edges[j].u] != INT_MAX &&
distance[edges[j].u] + edges[j].weight < distance[edges[j].v]) {
distance[edges[j].v] = distance[edges[j].u] + edges[j].weight;
}
}
// Recursive call for the next iteration
relaxEdges(edges, distance, edgesCount, iterations - 1);
}
// Function to implement Bellman-Ford algorithm (Recursive)
void bellmanFordRecursive(Edge edges[], int source) {
int distance[V];
// Step 1: Initialize distances
for (int i = 0; i < V; i++) {
distance[i] = INT_MAX;
}
distance[source] = 0;
// Step 2: Relax edges V - 1 times
relaxEdges(edges, distance, E, V - 1);
// Step 3: Print the shortest distances
printf("Vertex Distance from Source:\n");
for (int i = 0; i < V; i++) {
printf("%d \t\t %d\n", i, distance[i]);
}
}
int main() {
// Define edges of the graph
Edge edges[E] = {
{0, 1, -1},
{0, 2, 4},
{1, 2, 3},
{1, 3, 2},
{1, 4, 2},
{3, 2, 5},
{3, 1, 1},
{4, 3, -3}
};
int source = 0; // Starting vertex
bellmanFordRecursive(edges, source);
return 0;
}

Gyanmanjari College of Computer Application 29 | P a g e


Analysis and Design of Algorithm(MCAXX13516) 20230203010018

Gyanmanjari College of Computer Application 30 | P a g e

You might also like