SELECTION SORT
#include <stdio.h>
void selectionSort(int arr[], int n) {
int i, j, min_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++) {
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
// Swap the found minimum element with the first element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
void printArray(int arr[], int size) {
int i;
for (i=0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Original array: \n");
printArray(arr, n);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
....................................................................................................................................
TOWER OF HANOI
#include <stdio.h>
// Function to solve Tower of Hanoi problem
void towerOfHanoi(int n, char source, char auxiliary, char destination) {
if (n == 1) {
printf("Move disk 1 from rod %c to rod %c\n", source, destination);
return;
}
towerOfHanoi(n - 1, source, destination, auxiliary);
printf("Move disk %d from rod %c to rod %c\n", n, source, destination);
towerOfHanoi(n - 1, auxiliary, source, destination);
}
int main() {
int n = 3; // Number of disks
towerOfHanoi(n, ’A’, ’B’, ’C’); // A, B and C are names of rods
return 0;
}
..................................................................................................................................................
PERMUTATION OF A GIVEN STRING
#include <stdio.h>
#include <string.h>
// Function to swap characters at position i and j in string str
void swap(char *x, char *y) {
char temp = *x;
*x = *y;
*y = temp;
}
// Recursive function to generate all permutations of a string
void permute(char *str, int left, int right) {
if (left == right) {
printf("%s\n", str); // Print permutation when all characters are fixed
} else {
for (int i = left; i <= right; i++) {
swap((str + left), (str + i)); // Fix character at position left
permute(str, left + 1, right); // Recur for substring str[left+1..right]
swap((str + left), (str + i)); // Restore back to the original string
}
}
}
// Function to find all permutations of a string
void findAllPermutations(char *str) {
int n = strlen(str);
permute(str, 0, n - 1);
}
int main() {
char str[] = "ABC"; // Input string
printf("All permutations of %s are:\n", str);
findAllPermutations(str);
return 0;
}
....................................................................................................................................................
INSERTION SORT
#include <stdio.h>
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: \n");
printArray(arr, n);
insertionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
.................................................................................................................................................
BUBBLE SORT
#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j;
for (i = 0; i < n-1; i++) {
// Last i elements are already in place
for (j = 0; j < n-i-1; j++) {
// Swap if the element found is greater than the next element
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
void printArray(int arr[], int size) {
int i;
for (i=0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Original array: \n");
printArray(arr, n);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
....................................................................................................
MAGIC SQUARE
#include <stdio.h>
#include <stdlib.h>
// Function to generate Magic Square of order n (odd)
void generateMagicSquare(int n) {
int magicSquare[n][n];
// Initialize all elements of magic square to 0
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
magicSquare[i][j] = 0;
}
}
// Initialize position for 1
int i = n/2;
int j = n-1;
// Fill the magic square
for (int num = 1; num <= n * n;) {
if (i == -1 && j == n) {
j = n - 2;
i = 0;
} else {
if (j == n)
j = 0;
if (i < 0)
i = n - 1;
}
if (magicSquare[i][j]) {
j -= 2;
i++;
continue;
} else
magicSquare[i][j] = num++;
j++;
i--;
}
// Print the magic square
printf("The Magic Square for order %d:\nSum of each row/column/diagonal is %d:\n\n", n, n * (n * n + 1)
/ 2);
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
printf("%3d ", magicSquare[i][j]);
}
printf("\n");
}
}
int main() {
int n;
printf("Enter the order of Magic Square (odd number): ");
scanf("%d", &n);
if (n % 2 == 0) {
printf("Invalid input! Please enter an odd number.\n");
return 1;
}
generateMagicSquare(n);
return 0;
}
........................................................................................................................................................................
...........
POWER OF A NUMBER
#include <stdio.h>
double power(double base, int exponent) {
double result = 1.0;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
int main() {
double base;
int exponent;
printf("Enter base: ");
scanf("%lf", &base);
printf("Enter exponent: ");
scanf("%d", &exponent);
double result = power(base, exponent);
printf("%.2lf^%d = %.2lf\n", base, exponent, result);
return 0;
}
RECURSIVE
#include <stdio.h>
double power(double base, int exponent) {
if (exponent == 0) {
return 1.0;
} else if (exponent > 0) {
return base * power(base, exponent - 1);
} else {
// Negative exponent
return 1.0 / power(base, -exponent);
}
}
int main() {
double base;
int exponent;
printf("Enter base: ");
scanf("%lf", &base);
printf("Enter exponent: ");
scanf("%d", &exponent);
double result = power(base, exponent);
printf("%.2lf^%d = %.2lf\n", base, exponent, result);
return 0;
}
........................................................................................................................................................................
...............
LINEAR SEARCH
#include <stdio.h>
// Function to perform linear search
int linear_search(int array[], int size, int target) {
for (int i = 0; i < size; i++) {
if (array[i] == target) {
return i; // Return the index of the target element
}
}
return -1; // Return -1 if the target element is not found
}
int main() {
int array[] = {3, 5, 2, 4, 9, 1, 8};
int size = sizeof(array) / sizeof(array[0]);
int target = 4;
int result = linear_search(array, size, target);
if (result != -1) {
printf("Element %d found at index %d.\n", target, result);
} else {
printf("Element %d not found in the array.\n", target);
}
return 0;
}
........................................................................................................................................................................
...............
FIBONACCI SEQUENCE
#include <stdio.h>
// Function to generate Fibonacci sequence
void generate_fibonacci(int n) {
int first = 0, second = 1, next;
printf("Fibonacci sequence:\n");
for (int i = 0; i < n; i++) {
if (i <= 1) {
next = i;
} else {
next = first + second;
first = second;
second = next;
}
printf("%d ", next);
}
printf("\n");
}
int main() {
int n;
printf("Enter the number of terms: ");
scanf("%d", &n);
if (n <= 0) {
printf("Please enter a positive integer.\n");
} else {
generate_fibonacci(n);
}
return 0;
}
........................................................................................................................................................................
...........
FINDING EUIVALENT OF A DECIMAL NUMBERAND COUNTING TOTA BITS IN THE BINARY
NUMBER
#include <stdio.h>
// Function to convert decimal to binary and count the bits
void decimal_to_binary(int decimal, char *binary, int *bit_count) {
int index = 0;
int temp = decimal;
// If the number is 0, handle it separately
if (decimal == 0) {
binary[index++] = ’0’;
*bit_count = 1;
binary[index] = ’\0’;
return;
}
// Convert decimal to binary by continuously dividing by 2
while (temp > 0) {
binary[index++] = (temp % 2) + ’0’;
temp /= 2;
}
// Reverse the binary string to get the correct representation
for (int i = 0; i < index / 2; i++) {
char temp_char = binary[i];
binary[i] = binary[index - i - 1];
binary[index - i - 1] = temp_char;
}
// Null-terminate the binary string
binary[index] = ’\0’;
// Set the bit count
*bit_count = index;
}
int main() {
int decimal;
char binary[32]; // Assuming a maximum of 32 bits for the binary representation
int bit_count;
// Prompt user for input
printf("Enter a decimal number: ");
scanf("%d", &decimal);
// Convert decimal to binary and count bits
decimal_to_binary(decimal, binary, &bit_count);
// Print the results
printf("Binary equivalent: %s\n", binary);
printf("Total bits: %d\n", bit_count);
return 0;
}
........................................................................................................................................................................
.............
BINARY TREE WITH EVALUATION OF INSERTION INORDER,PREORDER, POST ORDER ,
LARGEST , SMALLEST , EXTERNAL , NODES , INTERNAL ETC
#include <stdio.h>
#include <stdlib.h>
// Definition of a tree node
struct Node {
int data;
struct Node *left, *right;
};
// Function to create a new tree node
struct Node* createNode(int data) {
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// Function to insert a node in the binary tree
struct Node* insert(struct Node* node, int data) {
if (node == NULL) return createNode(data);
if (data < node->data)
node->left = insert(node->left, data);
else if (data > node->data)
node->right = insert(node->right, data);
return node;
}
// Inorder traversal (Left, Root, Right)
void inorder(struct Node* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
// Preorder traversal (Root, Left, Right)
void preorder(struct Node* root) {
if (root != NULL) {
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
}
// Postorder traversal (Left, Right, Root)
void postorder(struct Node* root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
}
// Function to find the largest element in the binary tree
int findLargest(struct Node* node) {
struct Node* current = node;
while (current->right != NULL) {
current = current->right;
}
return current->data;
}
// Function to find the smallest element in the binary tree
int findSmallest(struct Node* node) {
struct Node* current = node;
while (current->left != NULL) {
current = current->left;
}
return current->data;
}
// Function to count external (leaf) nodes
int countExternalNodes(struct Node* node) {
if (node == NULL) return 0;
if (node->left == NULL && node->right == NULL) return 1;
return countExternalNodes(node->left) + countExternalNodes(node->right);
}
// Function to count internal nodes
int countInternalNodes(struct Node* node) {
if (node == NULL || (node->left == NULL && node->right == NULL)) return 0;
return 1 + countInternalNodes(node->left) + countInternalNodes(node->right);
}
// Main function to test the binary tree implementation
int main() {
struct Node* root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
printf("Inorder traversal: ");
inorder(root);
printf("\n");
printf("Preorder traversal: ");
preorder(root);
printf("\n");
printf("Postorder traversal: ");
postorder(root);
printf("\n");
printf("Largest element: %d\n", findLargest(root));
printf("Smallest element: %d\n", findSmallest(root));
printf("Number of external (leaf) nodes: %d\n", countExternalNodes(root));
printf("Number of internal nodes: %d\n", countInternalNodes(root));
return 0;
}
........................................................................................................................................................................
............
MAX,MIN FROM ARRAY USING DIVIDE AND CONQUER
#include <stdio.h>
#include <limits.h>
// Function to find the maximum and minimum in an array using divide and conquer
void findMaxMin(int arr[], int low, int high, int *max, int *min) {
if (low == high) {
// Only one element
*max = *min = arr[low];
} else if (high == low + 1) {
// Only two elements
if (arr[low] < arr[high]) {
*max = arr[high];
*min = arr[low];
} else {
*max = arr[low];
*min = arr[high];
}
} else {
// More than two elements
int mid = (low + high) / 2;
int max1, min1, max2, min2;
findMaxMin(arr, low, mid, &max1, &min1);
findMaxMin(arr, mid + 1, high, &max2, &min2);
// Combine results
*max = (max1 > max2) ? max1 : max2;
*min = (min1 < min2) ? min1 : min2;
}
}
int main() {
int arr[] = {12, 3, 5, 7, 19, -10, 22, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int max = INT_MIN;
int min = INT_MAX;
findMaxMin(arr, 0, n - 1, &max, &min);
printf("Maximum element: %d\n", max);
printf("Minimum element: %d\n", min);
return 0;
}
........................................................................................................................................................................
............
algo for binary search
ITERATIVE
#include <stdio.h>
// Function to perform binary search iteratively
int binarySearchIterative(int arr[], int size, int target) {
int left = 0, right = size - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
// Check if the target is present at mid
if (arr[mid] == target)
return mid;
// If the target is greater, ignore the left half
if (arr[mid] < target)
left = mid + 1;
// If the target is smaller, ignore the right half
else
right = mid - 1;
}
// Target is not present in the array
return -1;
}
int main() {
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 10;
int result = binarySearchIterative(arr, n, target);
if (result != -1)
printf("Element is present at index %d\n", result);
else
printf("Element is not present in the array\n");
return 0;
}
...........................
RECURSIVE
#include <stdio.h>
// Function to perform binary search recursively
int binarySearchRecursive(int arr[], int left, int right, int target) {
if (left <= right) {
int mid = left + (right - left) / 2;
// Check if the target is present at mid
if (arr[mid] == target)
return mid;
// If the target is greater, ignore the left half
if (arr[mid] < target)
return binarySearchRecursive(arr, mid + 1, right, target);
// If the target is smaller, ignore the right half
return binarySearchRecursive(arr, left, mid - 1, target);
}
// Target is not present in the array
return -1;
}
int main() {
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 10;
int result = binarySearchRecursive(arr, 0, n - 1, target);
if (result != -1)
printf("Element is present at index %d\n", result);
else
printf("Element is not present in the array\n");
return 0;
}
........................................................................................................................................................................
...................
QUICK SORT
#include <stdio.h>
// Function to swap two elements
void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
// Partition function to place the pivot element at the correct position
int partition(int arr[], int low, int high) {
int pivot = arr[high]; // Pivot element
int i = (low - 1); // Index of the smaller element
for (int j = low; j <= high - 1; j++) {
// If the current element is smaller than or equal to the pivot
if (arr[j] <= pivot) {
i++; // Increment index of the smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
// The main function that implements Quick Sort
void quickSort(int arr[], int low, int high) {
if (low < high) {
// Partition the array around the pivot element
int pi = partition(arr, low, high);
// Recursively sort the sub-arrays
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
// Function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Driver code
int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Unsorted array: \n");
printArray(arr, n);
quickSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
........................................................................................................................................................................
...................
RANDOMIZED QUICK SORT
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Function to swap two elements
void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
// Function to generate a random pivot index
int getRandomPivot(int low, int high) {
srand(time(NULL));
return low + rand() % (high - low + 1);
}
// Partition function to place the pivot element at the correct position
int partition(int arr[], int low, int high) {
int pivotIndex = getRandomPivot(low, high);
int pivot = arr[pivotIndex]; // Pivot element
// Move pivot to end
swap(&arr[pivotIndex], &arr[high]);
int i = low - 1; // Index of the smaller element
for (int j = low; j <= high - 1; j++) {
// If the current element is smaller than or equal to the pivot
if (arr[j] <= pivot) {
i++; // Increment index of the smaller element
swap(&arr[i], &arr[j]);
}
}
// Move pivot to its final position
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
// The main function that implements Randomized Quick Sort
void randomizedQuickSort(int arr[], int low, int high) {
if (low < high) {
// Partition the array around the pivot element
int pi = partition(arr, low, high);
// Recursively sort the sub-arrays
randomizedQuickSort(arr, low, pi - 1);
randomizedQuickSort(arr, pi + 1, high);
}
}
// Function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Driver code
int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Unsorted array: \n");
printArray(arr, n);
randomizedQuickSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
........................................................................................................................................................................
...................
COUNTING SORT
#include <stdio.h>
#include <stdlib.h>
// Function to find the maximum element in the array
int findMax(int arr[], int n) {
int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max)
max = arr[i];
}
return max;
}
// Function to perform Counting Sort
void countingSort(int arr[], int n) {
int max = findMax(arr, n);
int *count = (int *)calloc(max + 1, sizeof(int));
// Store count of each element
for (int i = 0; i < n; i++)
count[arr[i]]++;
// Modify the count array to store the actual position of the elements
for (int i = 1; i <= max; i++)
count[i] += count[i - 1];
// Build the sorted array
int *output = (int *)malloc(n * sizeof(int));
for (int i = n - 1; i >= 0; i--) {
output[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}
// Copy the sorted elements into the original array
for (int i = 0; i < n; i++)
arr[i] = output[i];
free(output);
free(count);
}
// Function to print an array
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Main function
int main() {
int arr[] = {4, 2, 2, 8, 3, 3, 1};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
printArray(arr, n);
countingSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
........................................................................................................................................................................
...................
HEAP SORT TECHNIQUUE USING MIN HEAP PROPERTY
#include <stdio.h>
// Function to swap two elements
void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
// Function to heapify a subtree rooted at index i
void minHeapify(int arr[], int n, int i) {
int smallest = i; // Initialize smallest as root
int left = 2 * i + 1; // left = 2*i + 1
int right = 2 * i + 2; // right = 2*i + 2
// If left child is smaller than root
if (left < n && arr[left] < arr[smallest])
smallest = left;
// If right child is smaller than smallest so far
if (right < n && arr[right] < arr[smallest])
smallest = right;
// If smallest is not root
if (smallest != i) {
swap(&arr[i], &arr[smallest]);
// Recursively heapify the affected sub-tree
minHeapify(arr, n, smallest);
}
}
// Function to perform heap sort
void heapSort(int arr[], int n) {
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
minHeapify(arr, n, i);
// One by one extract an element from heap
for (int i = n - 1; i > 0; i--) {
// Move current root to end
swap(&arr[0], &arr[i]);
// Call max heapify on the reduced heap
minHeapify(arr, i, 0);
}
}
// Function to print an array
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Main function
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
printArray(arr, n);
heapSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
........................................................................................................................................................................
...................
DEMONSTRATE ALL FOUR POSSIBLE ACTIONS OVER MAX PRIORITY QUEUE .
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_SIZE 100
// Structure to represent a max priority queue
typedef struct {
int *heap;
int size;
int capacity;
} MaxPriorityQueue;
// Function to create a new max priority queue
MaxPriorityQueue* createMaxPriorityQueue(int capacity) {
MaxPriorityQueue* pq = (MaxPriorityQueue*)malloc(sizeof(MaxPriorityQueue));
pq->heap = (int*)malloc(capacity * sizeof(int));
pq->size = 0;
pq->capacity = capacity;
return pq;
}
// Function to swap two elements
void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
// Function to heapify a subtree rooted at index i
void maxHeapify(int arr[], int n, int i) {
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // left = 2*i + 1
int right = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root
if (left < n && arr[left] > arr[largest])
largest = left;
// If right child is larger than largest so far
if (right < n && arr[right] > arr[largest])
largest = right;
// If largest is not root
if (largest != i) {
swap(&arr[i], &arr[largest]);
// Recursively heapify the affected sub-tree
maxHeapify(arr, n, largest);
}
}
// Function to insert a new element into the max priority queue
void insert(MaxPriorityQueue* pq, int key) {
if (pq->size == pq->capacity) {
printf("Overflow: Max Priority Queue is full\n");
return;
}
// Insert the new key at the end
int i = pq->size++;
pq->heap[i] = key;
// Fix the max heap property if it is violated
while (i != 0 && pq->heap[(i - 1) / 2] < pq->heap[i]) {
swap(&pq->heap[i], &pq->heap[(i - 1) / 2]);
i = (i - 1) / 2;
}
}
// Function to extract the maximum element from the max priority queue
int extractMax(MaxPriorityQueue* pq) {
if (pq->size <= 0) {
printf("Underflow: Max Priority Queue is empty\n");
return INT_MIN;
}
if (pq->size == 1) {
pq->size--;
return pq->heap[0];
}
// Store the maximum value and remove it from the heap
int root = pq->heap[0];
pq->heap[0] = pq->heap[pq->size - 1];
pq->size--;
// Fix the max heap property if it is violated
maxHeapify(pq->heap, pq->size, 0);
return root;
}
// Function to get the maximum element from the max priority queue without removing it
int peek(MaxPriorityQueue* pq) {
if (pq->size <= 0) {
printf("Max Priority Queue is empty\n");
return INT_MIN;
}
return pq->heap[0];
}
// Function to change the priority of a key in the max priority queue
void changePriority(MaxPriorityQueue* pq, int index, int newKey) {
if (index < 0 || index >= pq->size) {
printf("Invalid index\n");
return;
}
pq->heap[index] = newKey;
// Fix the max heap property if it is violated
while (index != 0 && pq->heap[(index - 1) / 2] < pq->heap[index]) {
swap(&pq->heap[index], &pq->heap[(index - 1) / 2]);
index = (index - 1) / 2;
}
}
// Function to print the elements of the max priority queue
void printMaxPriorityQueue(MaxPriorityQueue* pq) {
printf("Max Priority Queue: ");
for (int i = 0; i < pq->size; i++) {
printf("%d ", pq->heap[i]);
}
printf("\n");
}
// Main function
int main() {
MaxPriorityQueue* pq = createMaxPriorityQueue(MAX_SIZE);
insert(pq, 4);
insert(pq, 7);
insert(pq, 2);
insert(pq, 9);
printMaxPriorityQueue(pq);
int maxElement = extractMax(pq);
printf("Extracted max element: %d\n", maxElement);
printMaxPriorityQueue(pq);
int peekElement = peek(pq);
printf("Peeked max element: %d\n", peekElement);
changePriority(pq, 1, 12);
printMaxPriorityQueue(pq);
return 0;
}
........................................................................................................................................................................
...................
JOB SEQUENCE WITH DEADLINE
#include <stdio.h>
#include <stdlib.h>
// Structure to represent a job
typedef struct {
char id;
int deadline;
int profit;
} Job;
// Function to swap two jobs
void swap(Job* a, Job* b) {
Job t = *a;
*a = *b;
*b = t;
}
// Function to perform bubble sort based on profit in descending order
void sortByProfit(Job arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j].profit < arr[j + 1].profit) {
swap(&arr[j], &arr[j + 1]);
}
}
}
}
// Function to find the maximum deadline
int findMaxDeadline(Job arr[], int n) {
int max = arr[0].deadline;
for (int i = 1; i < n; i++) {
if (arr[i].deadline > max) {
max = arr[i].deadline;
}
}
return max;
}
// Function to find the maximum profit job sequence
void jobSequence(Job arr[], int n) {
sortByProfit(arr, n);
int maxDeadline = findMaxDeadline(arr, n);
// Array to store the result (schedule)
char result[maxDeadline];
int slot[maxDeadline];
// Initialize all slots as empty
for (int i = 0; i < maxDeadline; i++) {
result[i] = ’ ’;
slot[i] = -1;
}
// Fill the result array
for (int i = 0; i < n; i++) {
for (int j = arr[i].deadline - 1; j >= 0; j--) {
if (slot[j] == -1) {
slot[j] = i;
result[j] = arr[i].id;
break;
}
}
}
// Print the job sequence
printf("Job Sequence: ");
for (int i = 0; i < maxDeadline; i++) {
if (result[i] != ’ ’) {
printf("%c ", result[i]);
}
}
printf("\n");
}
// Main function
int main() {
Job arr[] = { {’a’, 4, 20}, {’b’, 1, 10}, {’c’, 1, 40}, {’d’, 1, 30} };
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original Job Array:\n");
printf("ID Deadline Profit\n");
for (int i = 0; i < n; i++) {
printf("%c %d %d\n", arr[i].id, arr[i].deadline, arr[i].profit);
}
printf("\n");
printf("Job sequence to maximize profit:\n");
jobSequence(arr, n);
return 0;
}
........................................................................................................................................................................
...................
TO FRACTIONAL KNAPSACK
#include <stdio.h>
#include <stdlib.h>
// Structure to represent an item
typedef struct {
int weight;
int value;
double ratio; // ratio of value to weight
} Item;
// Function to swap two items
void swap(Item* a, Item* b) {
Item t = *a;
*a = *b;
*b = t;
}
// Function to perform bubble sort based on ratio in descending order
void sortByRatio(Item arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j].ratio < arr[j + 1].ratio) {
swap(&arr[j], &arr[j + 1]);
}
}
}
}
// Function to find the maximum value that can be obtained
double fractionalKnapsack(Item arr[], int n, int capacity) {
// Sort items based on their value to weight ratio in descending order
sortByRatio(arr, n);
double totalValue = 0.0;
int remainingCapacity = capacity;
// Iterate through all items
for (int i = 0; i < n; i++) {
// If adding the entire item is possible
if (arr[i].weight <= remainingCapacity) {
totalValue += arr[i].value;
remainingCapacity -= arr[i].weight;
}
// If only a fraction of the item can be added
else {
totalValue += arr[i].ratio * remainingCapacity;
break;
}
}
return totalValue;
}
// Main function
int main() {
int capacity = 50;
Item arr[] = { {10, 60}, {20, 100}, {30, 120} };
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original Item Array:\n");
printf("Weight Value\n");
for (int i = 0; i < n; i++) {
printf("%d %d\n", arr[i].weight, arr[i].value);
}
printf("\n");
double maxValue = fractionalKnapsack(arr, n, capacity);
printf("Maximum value that can be obtained: %.2f\n", maxValue);
return 0;
}
........................................................................................................................................................................
....................
PROGRAM TO IMPLEMENT THE LARGER INTERGER MULTIPLICATION
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Function to reverse a string
void reverseString(char str[], int length) {
int start = 0;
int end = length - 1;
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
// Function to multiply two large integers represented as strings
char* multiply(char num1[], char num2[]) {
int len1 = strlen(num1);
int len2 = strlen(num2);
// Allocate memory to store the result
int* result = (int*)calloc(len1 + len2, sizeof(int));
// Multiply each digit of num1 with each digit of num2
for (int i = 0; i < len1; i++) {
for (int j = 0; j < len2; j++) {
result[i + j + 1] += (num1[i] - ’0’) * (num2[j] - ’0’);
}
}
// Process the result to handle carries
for (int i = len1 + len2 - 1; i > 0; i--) {
if (result[i] >= 10) {
result[i - 1] += result[i] / 10;
result[i] %= 10;
}
}
// Convert the result to a string
int size = len1 + len2;
char* finalResult = (char*)malloc((size + 1) * sizeof(char));
int index = 0;
int i = 0;
while (i < size && result[i] == 0) {
i++; // Skip leading zeros
}
while (i < size) {
finalResult[index++] = result[i] + ’0’;
i++;
}
finalResult[index] = ’\0’;
// Free dynamically allocated memory
free(result);
// Reverse the final result
reverseString(finalResult, index);
return finalResult;
}
// Main function
int main() {
char num1[] = "123456789";
char num2[] = "987654321";
printf("Number 1: %s\n", num1);
printf("Number 2: %s\n", num2);
char* result = multiply(num1, num2);
printf("Product: %s\n", result);
// Free dynamically allocated memory
free(result);
return 0;
}