Quick Sort
#include <stdio.h>
// Function to swap two elements
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Function to partition the array and return the pivot index
int partition(int arr[], int low, int high) {
int pivot = arr[high]; // Choosing the last element as the pivot
int i = low - 1; // Index of the smaller element
for (int j = low; j < high; j++) {
// If current element is smaller than or equal to pivot
if (arr[j] <= pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return i + 1;
}
// Function to implement Quick Sort
void quickSort(int arr[], int low, int high) {
if (low < high) {
// Partitioning index
int pi = partition(arr, low, high);
// Separately sort elements before and after partition
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");
}
// Main function
int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: \n");
printArray(arr, n);
quickSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
Selection sort
#include <stdio.h>
// Function to swap two elements
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Function to perform selection sort
void selectionSort(int arr[], int n) {
int i, j, min_index;
// Traverse through the entire array
for (i = 0; i < n - 1; i++) {
// Find the index of the minimum element in the unsorted part of the array
min_index = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min_index]) {
min_index = j;
}
}
// Swap the found minimum element with the first element
swap(&arr[min_index], &arr[i]);
}
}
// Function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Main function
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;
}
Insertion sort
#include <stdio.h>
// Function to perform insertion sort
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
// Move elements of arr[0..i-1], that are greater than key, to one position ahead of their
current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
// Function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Main function
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;
}
Heap Sort
#include <stdio.h>
// Function to swap two elements
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Function to heapify a subtree rooted with node i which is an index in arr[]
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 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
heapify(arr, n, largest);
}
}
// Function to perform heap sort
void heapSort(int arr[], int n) {
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(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
heapify(arr, i, 0);
}
}
// Function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; 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: \n");
printArray(arr, n);
heapSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
Radix Sort
#include <stdio.h>
// Function to get the maximum value in the array
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;
}
// Function to count sort based on a specific digit
void countSort(int arr[], int n, int exp) {
int output[n]; // Output array
int count[10] = {0};
// Store count of occurrences in count[]
for (int i = 0; i < n; i++) {
count[(arr[i] / exp) % 10]++;
}
// Change count[i] so that count[i] now contains the actual position of this digit in output[]
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]--;
}
// Copy the output array to arr[], so that arr[] now contains sorted numbers according to
current digit
for (int i = 0; i < n; i++) {
arr[i] = output[i];
}
}
// Function to perform Radix Sort
void radixSort(int arr[], int n) {
// Find the maximum number to know the number of digits
int max = getMax(arr, n);
// Perform counting sort for every digit, starting from the least significant digit
for (int exp = 1; max / exp > 0; exp *= 10) {
countSort(arr, n, exp);
}
}
// Function to print the 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[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: \n");
printArray(arr, n);
radixSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
Bubble Sort
#include <stdio.h>
// Function to perform bubble sort
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
// Last i elements are already in place, so we don't need to compare them
for (int 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;
}
}
}
}
// Function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Main function
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;
}
Knapsack
#include<stdio.h>
// Function to find the maximum of two integers
int max(int a, int b) {
return (a > b) ? a : b;
}
// Function to solve the knapsack problem
int knapSack(int W, int wt[], int val[], int n) {
int i, w;
int K[n + 1][W + 1];
// Build table K[][] in bottom-up manner
for (i = 0; i <= n; i++) {
for (w = 0; w <= W; w++) {
if (i == 0 || w == 0)
K[i][w] = 0;
else if (wt[i - 1] <= w)
K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]);
else
K[i][w] = K[i - 1][w];
}
}
return K[n][W];
}
// Main function
int main() {
int val[] = {60, 100, 120};
int wt[] = {10, 20, 30};
int W = 50;
int n = sizeof(val) / sizeof(val[0]);
printf("Maximum value that can be obtained is: %d\n", knapSack(W, wt, val, n));
return 0;
}
N queen problem
#include<stdio.h>
#define N 8 // Define the board size
// Function to print the solution
void printSolution(int board[N][N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d ", board[i][j]);
}
printf("\n");
}
}
// Function to check if a queen can be placed on board[row][col]
int isSafe(int board[N][N], int row, int col) {
int i, j;
// Check this row on the left side
for (i = 0; i < col; i++)
if (board[row][i])
return 0;
// Check upper diagonal on the left side
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return 0;
// Check lower diagonal on the left side
for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j])
return 0;
return 1;
}
// Function to solve N-Queens problem using backtracking
int solveNQUtil(int board[N][N], int col) {
// Base case: If all queens are placed then return true
if (col >= N)
return 1;
// Consider this column and try placing this queen in all rows one by one
for (int i = 0; i < N; i++) {
// Check if the queen can be placed on board[i][col]
if (isSafe(board, i, col)) {
// Place this queen in board[i][col]
board[i][col] = 1;
// Recur to place rest of the queens
if (solveNQUtil(board, col + 1))
return 1;
// If placing queen in board[i][col] doesn't lead to a solution, then remove queen from
board[i][col]
board[i][col] = 0; // Backtrack
}
}
// If the queen cannot be placed in any row in this column, then return false
return 0;
}
// Function to solve N-Queens problem
void solveNQ() {
int board[N][N] = {{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0}};
if (solveNQUtil(board, 0) == 0) {
printf("Solution does not exist");
return;
}
printSolution(board);
}
// Main function
int main() {
solveNQ();
return 0;
}
Tsp
#include <stdio.h>
#include <limits.h>
#define V 4 // Number of vertices in the graph
// Function to find the minimum of two numbers
int min(int x, int y) {
return (x < y) ? x : y;
}
// Function to solve the Traveling Salesman Problem using dynamic programming
int tsp(int graph[][V], int mask, int pos, int dp[][V]) {
// If all vertices have been visited, return the cost of going back to the starting city
if (mask == (1 << V) - 1) {
return graph[pos][0];
}
// If this sub-problem has already been solved
if (dp[mask][pos] != -1) {
return dp[mask][pos];
}
// Initialize minimum value
int ans = INT_MAX;
// Try to go to each city not visited yet
for (int city = 0; city < V; city++) {
// If city is not visited
if ((mask & (1 << city)) == 0) {
int newAns = graph[pos][city] + tsp(graph, mask | (1 << city), city, dp);
ans = min(ans, newAns);
}
}
return dp[mask][pos] = ans;
}
// Main function
int main() {
int graph[V][V] = {
{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}
};
// dp array to store the minimum cost
int dp[1 << V][V];
for (int i = 0; i < (1 << V); i++) {
for (int j = 0; j < V; j++) {
dp[i][j] = -1;
}
}
// Mask to keep track of visited vertices, start from 1st vertex (0th index)
int mask = 1;
int pos = 0; // Starting position
// Call the tsp function to find the minimum cost
int minCost = tsp(graph, mask, pos, dp);
printf("Minimum cost for the Traveling Salesman Problem: %d\n", minCost);
return 0;
}
Huffman
#include <stdio.h>
#include <stdlib.h>
// Define the maximum number of characters in the input
#define MAX_CHAR 256
// Define the structure for a Huffman tree node
struct MinHeapNode {
char data;
unsigned freq;
struct MinHeapNode *left, *right;
};
// Define a min heap structure
struct MinHeap {
unsigned size;
unsigned capacity;
struct MinHeapNode** array;
};
// Function to create a new min heap node
struct MinHeapNode* newNode(char data, unsigned freq) {
struct MinHeapNode* temp = (struct MinHeapNode*)malloc(sizeof(struct MinHeapNode));
temp->left = temp->right = NULL;
temp->data = data;
temp->freq = freq;
return temp;
}
// Function to create a min heap
struct MinHeap* createMinHeap(unsigned capacity) {
struct MinHeap* minHeap = (struct MinHeap*)malloc(sizeof(struct MinHeap));
minHeap->size = 0;
minHeap->capacity = capacity;
minHeap->array = (struct MinHeapNode**)malloc(minHeap->capacity * sizeof(struct
MinHeapNode*));
return minHeap;
}
// Function to swap two min heap nodes
void swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b) {
struct MinHeapNode* t = *a;
*a = *b;
*b = t;
}
// Function to heapify at given index
void minHeapify(struct MinHeap* minHeap, int idx) {
int smallest = idx;
int left = 2 * idx + 1;
int right = 2 * idx + 2;
if (left < minHeap->size && minHeap->array[left]->freq < minHeap->array[smallest]->freq)
smallest = left;
if (right < minHeap->size && minHeap->array[right]->freq < minHeap->array[smallest]->freq)
smallest = right;
if (smallest != idx) {
swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]);
minHeapify(minHeap, smallest);
}
}
// Function to check if size of heap is 1 or not
int isSizeOne(struct MinHeap* minHeap) {
return (minHeap->size == 1);
}
// Function to extract the minimum value node from heap
struct MinHeapNode* extractMin(struct MinHeap* minHeap) {
struct MinHeapNode* temp = minHeap->array[0];
minHeap->array[0] = minHeap->array[minHeap->size - 1];
--minHeap->size;
minHeapify(minHeap, 0);
return temp;
}
// Function to insert a new node to the heap
void insertMinHeap(struct MinHeap* minHeap, struct MinHeapNode* minHeapNode) {
++minHeap->size;
int i = minHeap->size - 1;
while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq) {
minHeap->array[i] = minHeap->array[(i - 1) / 2];
i = (i - 1) / 2;
}
minHeap->array[i] = minHeapNode;
}
// Function to build a min heap
void buildMinHeap(struct MinHeap* minHeap) {
int n = minHeap->size - 1;
int i;
for (i = (n - 1) / 2; i >= 0; --i)
minHeapify(minHeap, i);
}
// Function to print an array of size n
void printArr(int arr[], int n) {
int i;
for (i = 0; i < n; ++i)
printf("%d", arr[i]);
printf("\n");
}
// Function to check if given node is leaf
int isLeaf(struct MinHeapNode* root) {
return !(root->left) && !(root->right);
}
// Function to create a min heap of capacity equal to size and inserts all character of data[]
struct MinHeap* createAndBuildMinHeap(char data[], int freq[], int size) {
struct MinHeap* minHeap = createMinHeap(size);
for (int i = 0; i < size; ++i)
minHeap->array[i] = newNode(data[i], freq[i]);
minHeap->size = size;
buildMinHeap(minHeap);
return minHeap;
}
// Function to build Huffman tree
struct MinHeapNode* buildHuffmanTree(char data[], int freq[], int size) {
struct MinHeapNode *left, *right, *top;
struct MinHeap* minHeap = createAndBuildMinHeap(data, freq, size);
while (!isSizeOne(minHeap)) {
left = extractMin(minHeap);
right = extractMin(minHeap);
top = newNode('$', left->freq + right->freq);
top->left = left;
top->right = right;
insertMinHeap(minHeap, top);
}
return extractMin(minHeap);
}
// Function to print Huffman codes from the root of Huffman Tree
void printCodes(struct MinHeapNode* root, int arr[], int top) {
if (root->left) {
arr[top] = 0;
printCodes(root->left, arr, top + 1);
}
if (root->right) {
arr[top] = 1;
printCodes(root->right, arr, top + 1);
}
if (isLeaf(root)) {
printf("%c: ", root->data);
printArr(arr, top);
}
}
// Function to build Huffman Tree and print codes by traversing the built Huffman Tree
void HuffmanCodes(char data[], int freq[], int size) {
struct MinHeapNode* root = buildHuffmanTree(data, freq, size);
int arr[MAX_CHAR], top = 0;
printCodes(root, arr, top);
}
// Main function
int main() {
char data[] = {'a', 'b', 'c', 'd', 'e', 'f'};
int freq[] = {5, 9, 12, 13, 16, 45};
int size = sizeof(data) / sizeof(data[0]);
HuffmanCodes(data, freq, size);
return 0;
}
Floyd
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
#define V 4 // Number of vertices in the graph
#define INF INT_MAX // Define infinity as maximum integer value
// Function to print the solution matrix
void printSolution(int dist[][V]) {
printf("Shortest distances between every pair of vertices:\n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF)
printf("%7s", "INF");
else
printf("%7d", dist[i][j]);
}
printf("\n");
}
}
// Function to implement the Floyd-Warshall algorithm
void floydWarshall(int graph[][V]) {
int dist[V][V];
// Initialize the solution matrix same as input graph matrix
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
dist[i][j] = graph[i][j];
// Update dist[][] to include shortest path between every pair of vertices
for (int k = 0; k < V; k++) {
// Pick all vertices as source one by one
for (int i = 0; i < V; i++) {
// Pick all vertices as destination for the above picked source
for (int j = 0; j < V; j++) {
// If vertex k is on the shortest path from i to j, then update the value of dist[i][j]
if (dist[i][k] != INF && dist[k][j] != INF && dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
printSolution(dist);
}
// Main function
int main() {
// Example graph represented as an adjacency matrix
int graph[V][V] = { {0, 5, INF, 10},
{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0} };
floydWarshall(graph);
return 0;
}
Dijakstras
#include <stdio.h>
#include <limits.h>
#include <stdbool.h>
#define V 6 // Number of vertices in the graph
// Function to find the vertex with minimum distance value, from the set of vertices not yet
included in shortest path tree
int minDistance(int dist[], bool sptSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
// Function to print the constructed distance array
void printSolution(int dist[]) {
printf("Vertex \t\t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t %d\n", i, dist[i]);
}
// Function to implement Dijkstra's algorithm for a graph represented using adjacency matrix
void dijkstra(int graph[V][V], int src) {
int dist[V]; // The output array. dist[i] will hold the shortest distance from src to i
bool sptSet[V]; // sptSet[i] will be true if vertex i is included in shortest path tree or shortest
distance from src to i is finalized
// Initialize all distances as INFINITE and stpSet[] as false
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
// Distance of source vertex from itself is always 0
dist[src] = 0;
// Find shortest path for all vertices
for (int count = 0; count < V - 1; count++) {
// Pick the minimum distance vertex from the set of vertices not yet processed.
int u = minDistance(dist, sptSet);
// Mark the picked vertex as processed
sptSet[u] = true;
// Update dist value of the adjacent vertices of the picked vertex.
for (int v = 0; v < V; v++)
// Update dist[v] only if it is not in sptSet, there is an edge from u to v, and total weight of
path from src to v through u is smaller than current value of dist[v]
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
// Print the constructed distance array
printSolution(dist);
}
// Main function
int main() {
// Example graph represented as an adjacency matrix
int graph[V][V] = { {0, 4, 0, 0, 0, 0},
{4, 0, 8, 0, 0, 0},
{0, 8, 0, 7, 0, 4},
{0, 0, 7, 0, 9, 14},
{0, 0, 0, 9, 0, 10},
{0, 0, 4, 14, 10, 0} };
dijkstra(graph, 0);
return 0;
}
Ford fulk
#include <stdio.h>
#include <limits.h>
#include <stdbool.h>
#define V 6 // Number of vertices in the graph
// Function to implement Breadth-First Search (BFS) to find if there is a path from source to sink
bool bfs(int residualGraph[V][V], int source, int sink, int parent[]) {
bool visited[V];
for (int i = 0; i < V; i++)
visited[i] = false;
// Create a queue for BFS
int queue[V];
int front = -1, rear = -1;
queue[++rear] = source;
visited[source] = true;
parent[source] = -1;
// Standard BFS Loop
while (front != rear) {
int u = queue[++front];
for (int v = 0; v < V; v++) {
if (!visited[v] && residualGraph[u][v] > 0) {
queue[++rear] = v;
parent[v] = u;
visited[v] = true;
}
}
}
// If sink is reached in BFS, then there is a path from source to sink
return visited[sink];
}
// Function to implement the Ford-Fulkerson algorithm
int fordFulkerson(int graph[V][V], int source, int sink) {
int u, v;
// Create a residual graph and fill the residual graph with given capacities in the original graph
int residualGraph[V][V];
for (u = 0; u < V; u++)
for (v = 0; v < V; v++)
residualGraph[u][v] = graph[u][v];
int parent[V]; // This array is filled by BFS to store path
int maxFlow = 0; // There is no flow initially
// Augment the flow while there is a path from source to sink
while (bfs(residualGraph, source, sink, parent)) {
// Find minimum residual capacity of the edges along the path filled by BFS
int pathFlow = INT_MAX;
for (v = sink; v != source; v = parent[v]) {
u = parent[v];
pathFlow = (pathFlow < residualGraph[u][v]) ? pathFlow : residualGraph[u][v];
}
// Update residual capacities of the edges and reverse edges along the path
for (v = sink; v != source; v = parent[v]) {
u = parent[v];
residualGraph[u][v] -= pathFlow;
residualGraph[v][u] += pathFlow;
}
// Add path flow to overall flow
maxFlow += pathFlow;
}
return maxFlow;
}
// Main function
int main() {
// Example graph represented as an adjacency matrix
int graph[V][V] = { {0, 16, 13, 0, 0, 0},
{0, 0, 10, 12, 0, 0},
{0, 4, 0, 0, 14, 0},
{0, 0, 9, 0, 0, 20},
{0, 0, 0, 7, 0, 4},
{0, 0, 0, 0, 0, 0} };
printf("The maximum possible flow is %d\n", fordFulkerson(graph, 0, 5));
return 0;
}
Subset
#include <stdio.h>
#include <stdbool.h>
// Function to solve the Subset Sum problem using dynamic programming
bool isSubsetSum(int set[], int n, int sum) {
// Create a 2D array to store the subset sum results
bool dp[n + 1][sum + 1];
// Base case initialization
for (int i = 0; i <= n; i++)
dp[i][0] = true;
for (int i = 1; i <= sum; i++)
dp[0][i] = false;
// Fill the dp table in bottom-up manner
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= sum; j++) {
// If the current element is greater than the sum, exclude it
if (set[i - 1] > j)
dp[i][j] = dp[i - 1][j];
else // Otherwise, check if it is possible to achieve the sum including or excluding the
current element
dp[i][j] = dp[i - 1][j] || dp[i - 1][j - set[i - 1]];
}
}
return dp[n][sum]; // Return true if sum is possible, false otherwise
}
// Main function
int main() {
int set[] = {3, 34, 4, 12, 5, 2};
int sum = 9;
int n = sizeof(set) / sizeof(set[0]);
if (isSubsetSum(set, n, sum))
printf("Subset with sum %d exists\n", sum);
else
printf("No subset with sum %d exists\n", sum);
return 0;
}
Strassen
#include<stdio.h>
// Function to add two matrices
void addMatrix(int n, int A[n][n], int B[n][n], int C[n][n]) {
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
C[i][j] = A[i][j] + B[i][j];
}
// Function to subtract two matrices
void subtractMatrix(int n, int A[n][n], int B[n][n], int C[n][n]) {
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
C[i][j] = A[i][j] - B[i][j];
}
// Function to multiply two matrices using Strassen algorithm
void strassen(int n, int A[n][n], int B[n][n], int C[n][n]) {
if(n == 1) {
C[0][0] = A[0][0] * B[0][0];
return;
}
int newSize = n / 2;
int A11[newSize][newSize], A12[newSize][newSize], A21[newSize][newSize],
A22[newSize][newSize];
int B11[newSize][newSize], B12[newSize][newSize], B21[newSize][newSize],
B22[newSize][newSize];
int C11[newSize][newSize], C12[newSize][newSize], C21[newSize][newSize],
C22[newSize][newSize];
int P1[newSize][newSize], P2[newSize][newSize], P3[newSize][newSize],
P4[newSize][newSize], P5[newSize][newSize], P6[newSize][newSize], P7[newSize][newSize];
int temp1[newSize][newSize], temp2[newSize][newSize];
// Partitioning the matrices into sub-matrices
for(int i = 0; i < newSize; i++)
for(int j = 0; j < newSize; j++) {
A11[i][j] = A[i][j];
A12[i][j] = A[i][j + newSize];
A21[i][j] = A[i + newSize][j];
A22[i][j] = A[i + newSize][j + newSize];
B11[i][j] = B[i][j];
B12[i][j] = B[i][j + newSize];
B21[i][j] = B[i + newSize][j];
B22[i][j] = B[i + newSize][j + newSize];
}
// Calculating P1 to P7 recursively
subtractMatrix(newSize, B12, B22, temp1);
strassen(newSize, A11, temp1, P1); // P1 = A11 * (B12 - B22)
addMatrix(newSize, A11, A12, temp1);
strassen(newSize, temp1, B22, P2); // P2 = (A11 + A12) * B22
addMatrix(newSize, A21, A22, temp1);
strassen(newSize, temp1, B11, P3); // P3 = (A21 + A22) * B11
subtractMatrix(newSize, B21, B11, temp1);
strassen(newSize, A22, temp1, P4); // P4 = A22 * (B21 - B11)
addMatrix(newSize, A11, A22, temp1);
addMatrix(newSize, B11, B22, temp2);
strassen(newSize, temp1, temp2, P5); // P5 = (A11 + A22) * (B11 + B22)
subtractMatrix(newSize, A12, A22, temp1);
addMatrix(newSize, B21, B22, temp2);
strassen(newSize, temp1, temp2, P6); // P6 = (A12 - A22) * (B21 + B22)
subtractMatrix(newSize, A11, A21, temp1);
addMatrix(newSize, B11, B12, temp2);
strassen(newSize, temp1, temp2, P7); // P7 = (A11 - A21) * (B11 + B12)
// Calculating the resulting sub-matrices C11, C12, C21, C22
addMatrix(newSize, P5, P4, temp1);
subtractMatrix(newSize, temp1, P2, temp2);
addMatrix(newSize, temp2, P6, C11); // C11 = P5 + P4 - P2 + P6
addMatrix(newSize, P1, P2, C12); // C12 = P1 + P2
addMatrix(newSize, P3, P4, C21); // C21 = P3 + P4
addMatrix(newSize, P5, P1, temp1);
subtractMatrix(newSize, temp1, P3, temp2);
subtractMatrix(newSize, temp2, P7, C22); // C22 = P5 + P1 - P3 - P7
// Combining the resulting sub-matrices into the final matrix C
for(int i = 0; i < newSize; i++)
for(int j = 0; j < newSize; j++) {
C[i][j] = C11[i][j];
C[i][j + newSize] = C12[i][j];
C[i + newSize][j] = C21[i][j];
C[i + newSize][j + newSize] = C22[i][j];
}
}
// Function to print a matrix
void printMatrix(int n, int matrix[n][n]) {
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++)
printf("%d ", matrix[i][j]);
printf("\n");
}
}
// Main function
int main() {
int n = 4; // Size of the matrices (n x n)
int A[4][4] = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16} };
int B[4][4] = { {17, 18, 19, 20},
{21, 22, 23, 24},
{25, 26, 27, 28},
{29, 30, 31, 32} };
int C[4][4]; // Resultant matrix
// Multiply matrices using Strassen algorithm
strassen(n, A, B, C);
printf("Matrix A:\n");
printMatrix(n, A);
printf("\n");
printf("Matrix B:\n");
printMatrix(n, B);
printf("\n");
printf("Resultant Matrix C:\n");
printMatrix(n, C);
return 0;
}
Bellman
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
#define V 5 // Number of vertices in the graph
#define E 8 // Number of edges in the graph
// Structure to represent a weighted edge in the graph
struct Edge {
int src, dest, weight;
};
// Function to print the solution array
void printSolution(int dist[]) {
printf("Vertex \t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t %d\n", i, dist[i]);
}
// Function to find the shortest paths from a single source vertex to all other vertices using
Bellman-Ford algorithm
void bellmanFord(struct Edge* edges, int source) {
// Initialize distance array to store the shortest distance from the source vertex to each vertex
int dist[V];
for (int i = 0; i < V; i++)
dist[i] = INT_MAX;
dist[source] = 0; // Distance from source vertex to itself is always 0
// Relax all edges V-1 times
for (int i = 0; i < V - 1; i++) {
for (int j = 0; j < E; j++) {
int u = edges[j].src;
int v = edges[j].dest;
int weight = edges[j].weight;
if (dist[u] != INT_MAX && dist[u] + weight < dist[v])
dist[v] = dist[u] + weight;
}
}
// Check for negative-weight cycles
for (int i = 0; i < E; i++) {
int u = edges[i].src;
int v = edges[i].dest;
int weight = edges[i].weight;
if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) {
printf("Graph contains negative-weight cycle.\n");
return;
}
}
// Print the shortest distances
printSolution(dist);
}
// Main function
int main() {
// Example graph represented using edge list
struct Edge edges[] = {
// src, dest, weight
{0, 1, -1},
{0, 2, 4},
{1, 2, 3},
{1, 3, 2},
{1, 4, 2},
{3, 2, 5},
{3, 1, 1},
{4, 3, -3}
};
// Source vertex
int source = 0;
// Call Bellman-Ford algorithm to find shortest paths
bellmanFord(edges, source);
return 0;
}
Puzzle
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define N 3 // Size of the puzzle (N x N)
#define EMPTY_TILE 0 // Value representing the empty tile
// Structure to represent a state of the puzzle
typedef struct {
int puzzle[N][N]; // Configuration of the puzzle
int cost; // Cost of reaching this state from the initial state
int heuristic; // Heuristic value (estimated cost to reach the goal state)
int row; // Row index of the empty tile
int col; // Column index of the empty tile
} State;
// Function to initialize a state with the given puzzle configuration
State initState(int puzzle[N][N]) {
State state;
state.cost = 0;
state.heuristic = 0;
// Copy puzzle configuration
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++) {
state.puzzle[i][j] = puzzle[i][j];
if (puzzle[i][j] == EMPTY_TILE) {
state.row = i;
state.col = j;
}
}
return state;
}
// Function to check if the puzzle is in the goal state
bool isGoalState(State state) {
int value = 1;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++) {
if (state.puzzle[i][j] != value && !(i == N - 1 && j == N - 1))
return false;
value++;
}
return true;
}
// Function to calculate the Manhattan distance between two tiles
int manhattanDistance(int x1, int y1, int x2, int y2) {
return abs(x1 - x2) + abs(y1 - y2);
}
// Function to calculate the heuristic value (total Manhattan distance) for a state
int calculateHeuristic(State state) {
int h = 0;
int value = 1;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++) {
if (state.puzzle[i][j] != value && state.puzzle[i][j] != EMPTY_TILE) {
int targetRow = (state.puzzle[i][j] - 1) / N;
int targetCol = (state.puzzle[i][j] - 1) % N;
h += manhattanDistance(i, j, targetRow, targetCol);
}
value++;
}
return h;
}
// Function to swap two tiles in the puzzle
void swapTiles(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Function to generate successor states by moving the empty tile
void generateSuccessors(State state, State successors[]) {
int row = state.row;
int col = state.col;
int index = 0;
// Move empty tile left
if (col > 0) {
swapTiles(&state.puzzle[row][col], &state.puzzle[row][col - 1]);
successors[index++] = state;
swapTiles(&state.puzzle[row][col], &state.puzzle[row][col - 1]); // Restore puzzle
configuration
}
// Move empty tile right
if (col < N - 1) {
swapTiles(&state.puzzle[row][col], &state.puzzle[row][col + 1]);
successors[index++] = state;
swapTiles(&state.puzzle[row][col], &state.puzzle[row][col + 1]); // Restore puzzle
configuration
}
// Move empty tile up
if (row > 0) {
swapTiles(&state.puzzle[row][col], &state.puzzle[row - 1][col]);
successors[index++] = state;
swapTiles(&state.puzzle[row][col], &state.puzzle[row - 1][col]); // Restore puzzle
configuration
}
// Move empty tile down
if (row < N - 1) {
swapTiles(&state.puzzle[row][col], &state.puzzle[row + 1][col]);
successors[index++] = state;
swapTiles(&state.puzzle[row][col], &state.puzzle[row + 1][col]); // Restore puzzle
configuration
}
}
// Function to print the puzzle configuration
void printPuzzle(State state) {
printf("Puzzle Configuration:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
printf("%d\t", state.puzzle[i][j]);
printf("\n");
}
}
// Function to solve the N-puzzle problem using A* search
void solvePuzzle(int initial[N][N]) {
State initial_state = initState(initial);
// Priority queue or any suitable data structure to store states based on their cost + heuristic
value
// Implementing a basic linear search for simplicity
State queue[10000];
int front = -1, rear = -1;
queue[++rear] = initial_state;
while (front != rear) {
State current = queue[++front];
if (isGoalState(current)) {
printf("Goal State Reached!\n");
printPuzzle(current);
return;
}
State successors[4]; // Max number of successors for a state (at most 4)
generateSuccessors(current, successors);
for (int i = 0; i < 4; i++) {
if (successors[i].puzzle[0][0] == 0) // Skip invalid successors
continue;
successors[i].cost = current.cost + 1; // Cost of reaching this state from initial state
successors[i].heuristic = calculateHeuristic(successors[i]);
queue[++rear] = successors[i];
}
// Bubble sort to maintain the priority queue based on cost + heuristic value
for (int i = front + 1; i < rear; i++)
for (int j = front + 1; j < rear; j++)
if (queue[j].cost + queue[j].heuristic > queue[j + 1].cost + queue[j + 1].heuristic) {
State temp = queue[j];
queue[j] = queue[j + 1];
queue[j + 1] = temp;
}
}
printf("No solution found!\n");
}
// Main function
int main() {
int puzzle[N][N] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 0} }; // Example puzzle configuration
solvePuzzle(puzzle);
return 0;
}
Graph color
#include <stdio.h>
#include <stdbool.h>
#define V 4 // Number of vertices in the graph
// Function to check if it's safe to assign color c to vertex v
bool isSafe(int v, bool graph[V][V], int color[], int c) {
for (int i = 0; i < V; i++) {
if (graph[v][i] && c == color[i])
return false;
}
return true;
}
// Function to recursively solve graph coloring using backtracking
bool graphColoringUtil(bool graph[V][V], int m, int color[], int v) {
if (v == V) // All vertices are colored
return true;
for (int c = 1; c <= m; c++) {
if (isSafe(v, graph, color, c)) {
color[v] = c;
// Recur for the next vertex
if (graphColoringUtil(graph, m, color, v + 1))
return true;
// If assigning color c doesn't lead to a solution, backtrack
color[v] = 0;
}
}
return false;
}
// Function to print the solution (colors assigned to vertices)
void printSolution(int color[]) {
printf("Vertex\tColor\n");
for (int i = 0; i < V; i++)
printf("%d\t%d\n", i, color[i]);
}
// Function to solve the graph coloring problem
bool graphColoring(bool graph[V][V], int m) {
int color[V];
for (int i = 0; i < V; i++)
color[i] = 0; // Initialize all vertices as unassigned
// Call the recursive utility function to solve the problem
if (!graphColoringUtil(graph, m, color, 0)) {
printf("Solution does not exist\n");
return false;
}
// Print the solution
printf("Solution exists\n");
printSolution(color);
return true;
}
// Main function
int main() {
bool graph[V][V] = {
{0, 1, 1, 1},
{1, 0, 1, 0},
{1, 1, 0, 1},
{1, 0, 1, 0}
};
int m = 3; // Number of colors
graphColoring(graph, m);
return 0;
}
Merge sort
#include <stdio.h>
// Function to merge two subarrays arr[l..m] and arr[m+1..r] into one sorted array
void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1; // Size of the left subarray
int n2 = r - m; // Size of the right subarray
// Create temporary arrays
int L[n1], R[n2];
// Copy data to temporary arrays L[] and R[]
for (int i = 0; i < n1; i++)
L[i] = arr[l + i];
for (int j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
// Merge the temporary arrays back into arr[l..r]
int i = 0, j = 0, k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
// Copy the remaining elements of L[], if any
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++;
}
}
// Function to perform merge sort on array arr[l..r]
void mergeSort(int arr[], int l, int r) {
if (l < r) {
// Find the middle point
int m = l + (r - l) / 2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
// Function to print an array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Main function
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr) / sizeof(arr[0]);
printf("Given array is \n");
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
printf("\nSorted array is \n");
printArray(arr, arr_size);
return 0;
}
Linear search
#include <stdio.h>
// Function to perform linear search
int linearSearch(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
return i; // Return the index if target is found
}
}
return -1; // Return -1 if target is not found
}
// Main function
int main() {
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 10;
int index = linearSearch(arr, n, target);
if (index != -1) {
printf("Element %d found at index %d\n", target, index);
} else {
printf("Element %d not found in the array\n", target);
}
return 0;
}
B