0% found this document useful (0 votes)
15 views21 pages

Kappa

The document contains implementations of various sorting algorithms (Selection Sort, Insertion Sort, Merge Sort, Quick Sort) and graph algorithms (Dijkstra's Algorithm, Prim's Algorithm, Kruskal's Algorithm, Bellman-Ford Algorithm) in C. Each algorithm is presented with its respective code, demonstrating how to sort arrays or find shortest paths in graphs. The examples include printing sorted arrays and distances from a source vertex.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views21 pages

Kappa

The document contains implementations of various sorting algorithms (Selection Sort, Insertion Sort, Merge Sort, Quick Sort) and graph algorithms (Dijkstra's Algorithm, Prim's Algorithm, Kruskal's Algorithm, Bellman-Ford Algorithm) in C. Each algorithm is presented with its respective code, demonstrating how to sort arrays or find shortest paths in graphs. The examples include printing sorted arrays and distances from a source vertex.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Selection Sort :

#include <stdio.h>

void selectionSort(int arr[], int n) {


​ int i, j, minIndex, temp;

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


​ ​ minIndex = i;
​ for (j = i + 1; j < n; j++) {
​ if (arr[j] < arr[minIndex]) {
​ minIndex = j;
​ }
​ }


​ if (minIndex != i) {
​ temp = arr[i];
​ arr[i] = arr[minIndex];
​ arr[minIndex] = temp;
​ }
​ }
}

void printArray(int arr[], int size) {


​ for (int 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("Unsorted array: ");


​ printArray(arr, n);

​ selectionSort(arr, n);

​ printf("Sorted array: ");


​ printArray(arr, n);

​ 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;
​ while (j >= 0 && arr[j] > key) {
​ arr[j + 1] = arr[j];
​ j = j - 1;
​ }
​ arr[j + 1] = key;
​ }
}

void printArray(int arr[], int size) {


​ for (int 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("Unsorted array: ");


​ printArray(arr, n);

​ insertionSort(arr, n);

​ printf("Sorted array: ");


​ printArray(arr, n);

​ return 0;
}
Merge Sort :

#include <stdio.h>
#include <limits.h>

void merge(int arr[], int temp[], int left, int mid, int right, int *min, int *max) {
​ int i = left, j = mid + 1, k = left;

​ while (i <= mid && j <= right) {


​ if (arr[i] <= arr[j]) {
​ temp[k++] = arr[i++];
​ } else {
​ temp[k++] = arr[j++];
​ }
​ }

​ while (i <= mid) {


​ temp[k++] = arr[i++];
​ }

​ while (j <= right) {


​ temp[k++] = arr[j++];
​ }

​ for (i = left; i <= right; i++) {


​ arr[i] = temp[i];
​ }

​ // Update minimum and maximum values after merge


​ for (i = left; i <= right; i++) {
​ if (arr[i] < *min) {
​ *min = arr[i];
​ }
​ if (arr[i] > *max) {
​ *max = arr[i];
​ }
​ }
}

void mergeSort(int arr[], int temp[], int left, int right, int *min, int *max) {
​ if (left < right) {
​ int mid = left + (right - left) / 2;

​ mergeSort(arr, temp, left, mid, min, max);


​ mergeSort(arr, temp, mid + 1, right, min, max);

​ merge(arr, temp, left, mid, right, min, max);


​ }
}

int main() {
​ int arr[] = {64, 25, 12, 22, 11};
​ int n = sizeof(arr) / sizeof(arr[0]);
​ int temp[n];

​ int min = INT_MAX;


​ int max = INT_MIN;

​ mergeSort(arr, temp, 0, n - 1, &min, &max);

​ printf("Sorted array: ");


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

​ printf("Minimum value: %d\n", min);


​ printf("Maximum value: %d\n", max);

​ return 0;
}

Quick Sort :

#include <stdio.h>
#include <limits.h>

void swap(int *a, int *b) {


​ int temp = *a;
​ *a = *b;
​ *b = temp;
}

int partition(int arr[], int low, int high) {


​ int pivot = arr[high];
​ int i = low - 1;
​ for (int j = low; j < high; j++) {
​ if (arr[j] <= pivot) {
​ i++;
​ swap(&arr[i], &arr[j]);
​ }
​ }
​ swap(&arr[i + 1], &arr[high]);
​ return i + 1;
}

void quickSort(int arr[], int low, int high, int *min, int *max) {
​ if (low < high) {
​ int pi = partition(arr, low, high);

​ quickSort(arr, low, pi - 1, min, max);


​ quickSort(arr, pi + 1, high, min, max);
​ }

​ ​ for (int i = low; i <= high; i++) {


​ if (arr[i] < *min) {
​ *min = arr[i];
​ }
​ if (arr[i] > *max) {
​ *max = arr[i];
​ }
​ }
}

int main() {
​ int arr[] = {64, 25, 12, 22, 11};
​ int n = sizeof(arr) / sizeof(arr[0]);

​ int min = INT_MAX;


​ int max = INT_MIN;

​ quickSort(arr, 0, n - 1, &min, &max);

​ printf("Sorted array: ");


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

​ printf("Minimum value: %d\n", min);


​ printf("Maximum value: %d\n", max);
​ return 0;
}

Single Source Shortest Path (Dijkstra) :

#include <stdio.h>
#include <limits.h>

#define V 9

int minDistance(int dist[], int sptSet[]) {


​ int min = INT_MAX, min_index;
​ for (int v = 0; v < V; v++) {
​ if (sptSet[v] == 0 && dist[v] <= min) {
​ min = dist[v];
​ min_index = v;
​ }
​ }
​ return min_index;
}

void dijkstra(int graph[V][V], int src) {


​ int dist[V];
​ int sptSet[V];
​ for (int i = 0; i < V; i++) {
​ dist[i] = INT_MAX;
​ sptSet[i] = 0;
​ }
​ dist[src] = 0;
​ for (int count = 0; count < V - 1; count++) {
​ int u = minDistance(dist, sptSet);
​ sptSet[u] = 1;
​ for (int v = 0; v < V; v++) {
​ if (graph[u][v] && sptSet[v] == 0 && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v])
{
​ dist[v] = dist[u] + graph[u][v];
​ }
​ }
​ }
​ printf("Vertex\tDistance from Source\n");
​ for (int i = 0; i < V; i++) {
​ printf("%d\t%d\n", i, dist[i]);
​ }
}

int main() {
​ int graph[V][V] = {
​ {0, 4, 0, 0, 0, 0, 0, 8, 0},
​ {4, 0, 8, 0, 0, 0, 0, 0, 0},
​ {0, 8, 0, 7, 0, 4, 0, 0, 0},
​ {0, 0, 7, 0, 9, 14, 0, 0, 0},
​ {0, 0, 0, 9, 0, 10, 0, 0, 0},
​ {0, 0, 4, 14, 10, 0, 2, 0, 0},
​ {0, 0, 0, 0, 0, 2, 0, 1, 6},
​ {8, 0, 0, 0, 0, 0, 1, 0, 7},
​ {0, 0, 0, 0, 0, 0, 6, 7, 0}
​ };
​ int source = 0;
​ dijkstra(graph, source);
​ return 0;
}

Prims Algo :
#include <stdio.h>
#include <limits.h>

#define V 5

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;
}

void primMST(int graph[V][V]) {


​ int parent[V];
​ int key[V];
​ int mstSet[V];
​ for (int i = 0; i < V; i++) {
​ key[i] = INT_MAX;
​ mstSet[i] = 0;
​ }
​ key[0] = 0;
​ parent[0] = -1;

​ for (int count = 0; count < V - 1; count++) {


​ int u = minKey(key, mstSet);
​ mstSet[u] = 1;

​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];
​ }
​ }
​ }

​ 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() {
​ 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;
}

Kruskals Algo :

#include <stdio.h>
#include <stdlib.h>

#define V 5
#define E 7

typedef struct {
​ int u, v, weight;
} Edge;

int parent[V];
int rank[V];

int find(int i) {
​ if (parent[i] == i)
​ return i;
​ return parent[i] = find(parent[i]);
}

void union_sets(int x, int y) {


​ int rootX = find(x);
​ int rootY = find(y);

​ if (rootX != rootY) {
​ if (rank[rootX] > rank[rootY]) {
​ parent[rootY] = rootX;
​ } else if (rank[rootX] < rank[rootY]) {
​ parent[rootX] = rootY;
​ } else {
​ parent[rootY] = rootX;
​ rank[rootX]++;
​ }
​ }
}

int compareEdges(const void *a, const void *b) {


​ return ((Edge *)a)->weight - ((Edge *)b)->weight;
}

void kruskalMST(Edge edges[], int edgeCount) {


​ for (int i = 0; i < V; i++) {
​ parent[i] = i;
​ rank[i] = 0;
​ }

​ qsort(edges, edgeCount, sizeof(Edge), compareEdges);

​ int mstWeight = 0;
​ printf("Edge \tWeight\n");
​ for (int i = 0; i < edgeCount; i++) {
​ int u = edges[i].u;
​ int v = edges[i].v;
​ int weight = edges[i].weight;

​ int rootU = find(u);
​ int rootV = find(v);

​if (rootU != rootV) {
​ printf("%d - %d \t%d\n", u, v, weight);
​ mstWeight += weight;
​ union_sets(rootU, rootV);
​ }
​ }
​ printf("Total weight of MST: %d\n", mstWeight);
}

int main() {
​ Edge edges[E] = {
​ {0, 1, 2}, {0, 3, 6}, {1, 2, 3}, {1, 3, 8},
​ {1, 4, 5}, {2, 4, 7}, {3, 4, 9}
​ };

​ kruskalMST(edges, E);
​ return 0;
}

Bellman Ford :
#include <stdio.h>
#include <limits.h>

#define V 5 // Number of vertices


#define E 8 // Number of edges

typedef struct {
​ int u, v, weight;
} Edge;

void bellmanFord(Edge edges[], int src) {


​ int dist[V];

​ ​ for (int i = 0; i < V; i++) {


​ dist[i] = INT_MAX;
​ }
​ dist[src] = 0;
​ ​ for (int i = 1; i <= V - 1; i++) {
​ for (int j = 0; j < E; j++) {
​ int u = edges[j].u;
​ int v = edges[j].v;
​ int weight = edges[j].weight;
​ if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) {
​ dist[v] = dist[u] + weight;
​ }
​ }
​ }

​ for (int i = 0; i < E; i++) {


​ int u = edges[i].u;
​ int v = edges[i].v;
​ int weight = edges[i].weight;
​ if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) {
​ printf("Graph contains negative weight cycle\n");
​ return;
​ }
​ }

​ printf("Vertex\tDistance from Source\n");


​ for (int i = 0; i < V; i++) {
​ if (dist[i] == INT_MAX) {
​ printf("%d\tINF\n", i);
​ } else {
​ printf("%d\t%d\n", i, dist[i]);
​ }
​ }
}

int main() {
​ Edge edges[E] = {
​ {0, 1, -1}, {0, 2, 4}, {1, 2, 3}, {1, 3, 2},
​ {1, 4, 2}, {3, 2, 5}, {3, 4, -3}, {4, 3, 3}
​ };

​ int source = 0;
​ bellmanFord(edges, source);

​ return 0;
}

N-Queen :
#include <stdio.h>
#include <stdbool.h>

#define N 4

int board[N][N];

bool isSafe(int row, int col) {


​ for (int i = 0; i < col; i++) {
​ if (board[row][i] == 1) {
​ return false;
​ }
​ }
​ for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
​ if (board[i][j] == 1) {
​ return false;
​ }
​ }
​ for (int i = row, j = col; j >= 0 && i < N; i++, j--) {
​ if (board[i][j] == 1) {
​ return false;
​ }
​ }
​ return true;
}

bool solveNQueen(int col) {


​ if (col >= N) {
​ return true;
​ }
​ for (int i = 0; i < N; i++) {
​ if (isSafe(i, col)) {
​ board[i][col] = 1;
​ if (solveNQueen(col + 1)) {
​ return true;
​ }
​ board[i][col] = 0;
​ }
​ }
​ return false;
}

void printBoard() {
​ for (int i = 0; i < N; i++) {
​ for (int j = 0; j < N; j++) {
​ printf("%d ", board[i][j]);
​ }
​ printf("\n");
​ }
}

int main() {
​ for (int i = 0; i < N; i++) {
​ for (int j = 0; j < N; j++) {
​ board[i][j] = 0;
​ }
​ }
​ if (solveNQueen(0)) {
​ printBoard();
​ } else {
​ printf("Solution does not exist\n");
​ }
​ return 0;
}

Graph Coloring :
#include <stdio.h>
#include <stdbool.h>

#define V 4
bool isSafe(int graph[V][V], int color[], int v, int c) {
​ for (int i = 0; i < V; i++) {
​ if (graph[v][i] && color[i] == c) {
​ return false;
​ }
​ }
​ return true;
}

bool graphColoring(int graph[V][V], int m, int color[], int v) {


​ if (v == V) {
​ return true;
​ }
​ for (int c = 1; c <= m; c++) {
​ if (isSafe(graph, color, v, c)) {
​ color[v] = c;
​ if (graphColoring(graph, m, color, v + 1)) {
​ return true;
​ }
​ color[v] = 0; ​ }
​ }
​ return false;
}

void printSolution(int color[]) {


​ printf("Solution exists: The colors assigned to the vertices are:\n");
​ for (int i = 0; i < V; i++) {
​ printf("Vertex %d -> Color %d\n", i, color[i]);
​ }
}

int main() {
​ int graph[V][V] = {
​ {0, 1, 1, 1},
​ {1, 0, 1, 0},
​ {1, 1, 0, 1},
​ {1, 0, 1, 0}
​ };
​ int m = 3;
​ int color[V] = {0};
​ if (graphColoring(graph, m, color, 0)) {
​ printSolution(color);
​ } else {
​ printf("Solution does not exist\n");
​ }

​ return 0;
}

Naive String Matching :


#include <stdio.h>
#include <string.h>

void naiveStringMatch(char text[], char pattern[]) {


​ int n = strlen(text);
​ int m = strlen(pattern);

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


​ int j = 0;

​ while (j < m && text[i + j] == pattern[j]) {
​ j++;
​ }

​ if (j == m) {
​ printf("Pattern found at index %d\n", i);
​ }
​ }
}

int main() {
​ char text[] = "ABABDABACDABABCABAB";
​ char pattern[] = "ABAB";

​ naiveStringMatch(text, pattern);
​ return 0;
}

KnapSack Using Greedy :


#include <stdio.h>

struct Item {
​ int value;
​ int weight;
​ float ratio;
};

void swap(struct Item *a, struct Item *b) {


​ struct Item temp = *a;
​ *a = *b;
​ *b = temp;
}

void sort(struct Item arr[], int n) {


​ for (int i = 0; i < n-1; i++) {
​ for (int j = i+1; j < n; j++) {
​ if (arr[i].ratio < arr[j].ratio) {
​ swap(&arr[i], &arr[j]);
​ }
​ }
​ }
}

float knapsack(struct Item items[], int n, int W) {


​ sort(items, n);
​ int currentWeight = 0;
​ float totalValue = 0.0;

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


​ if (currentWeight + items[i].weight <= W) {
​ currentWeight += items[i].weight;
​ totalValue += items[i].value;
​ } else {
​ int remainingWeight = W - currentWeight;
​ totalValue += items[i].value * ((float)remainingWeight / items[i].weight);
​ break;
​ }
​ }

​ return totalValue;
}

int main() {
​ struct Item items[] = {{60, 10, 0}, {100, 20, 0}, {120, 30, 0}};
​ int n = sizeof(items) / sizeof(items[0]);
​ int W = 50;

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


​ items[i].ratio = (float)items[i].value / items[i].weight;
​ }

​ float maxValue = knapsack(items, n, W);


​ printf("Maximum value we can obtain = %.2f\n", maxValue);

​ return 0;
}

Floyd Warshall :

#include <stdio.h>
#include <limits.h>

#define V 4
void printSolution(int dist[V][V]) {
​ printf("The shortest distances between every pair of vertices are:\n");
​ for (int i = 0; i < V; i++) {
​ for (int j = 0; j < V; j++) {
​ if (dist[i][j] == INT_MAX) {
​ printf("INF ");
​ } else {
​ printf("%d ", dist[i][j]);
​ }
​ }
​ printf("\n");
​ }
}

void floydWarshall(int graph[V][V]) {


​ int dist[V][V];

​ ​ for (int i = 0; i < V; i++) {


​ for (int j = 0; j < V; j++) {
​ if (graph[i][j] == 0 && i != j) {
​ dist[i][j] = INT_MAX;
​ } else {
​ dist[i][j] = graph[i][j];
​ }
​ }
​ }

​ ​ for (int k = 0; k < V; k++) {


​ for (int i = 0; i < V; i++) {
​ for (int j = 0; j < V; j++) {
​ if (dist[i][k] != INT_MAX && dist[k][j] != INT_MAX &&
​ dist[i][j] > dist[i][k] + dist[k][j]) {
​ dist[i][j] = dist[i][k] + dist[k][j];
​ }
​ }
​ }
​ }

​ printSolution(dist);
}

int main() {
​ int graph[V][V] = {
​ {0, 3, 0, 0},
​ {3, 0, 1, 0},
​ {0, 1, 0, 7},
​ {0, 0, 7, 0}
​ };
​ floydWarshall(graph);

​ return 0;
}

15 Puzzle Problem :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define N 4
#define MAX_QUEUE_SIZE 1000

typedef struct {
​ int state[N][N];
​ int cost; ​ int heuristic; // Heuristic cost (Manhattan distance)
​ int emptyX, emptyY; // Position of the empty space
} Node;

typedef struct {
​ Node nodes[MAX_QUEUE_SIZE];
​ int front, rear;
} Queue;

Queue q;

void initQueue() {
​ q.front = q.rear = -1;
}

int isQueueEmpty() {
​ return q.front == -1;
}

int isQueueFull() {
​ return q.rear == MAX_QUEUE_SIZE - 1;
}

void enqueue(Node node) {


​ if (isQueueFull()) return;
​ if (q.front == -1) q.front = 0;
​ q.rear++;
​ q.nodes[q.rear] = node;
}
Node dequeue() {
​ Node node = {-1};
​ if (!isQueueEmpty()) {
​ node = q.nodes[q.front];
​ q.front++;
​ if (q.front > q.rear) q.front = q.rear = -1;
​ }
​ return node;
}

int isGoalState(Node node) {


​ int goalState[N][N] = {
​ {1, 2, 3, 4},
​ {5, 6, 7, 8},
​ {9, 10, 11, 12},
​ {13, 14, 15, 0}
​ };

​ for (int i = 0; i < N; i++) {


​ for (int j = 0; j < N; j++) {
​ if (node.state[i][j] != goalState[i][j]) {
​ return 0;
​ }
​ }
​ }
​ return 1;
}

int calculateHeuristic(Node node) {


​ int h = 0;
​ for (int i = 0; i < N; i++) {
​ for (int j = 0; j < N; j++) {
​ int tile = node.state[i][j];
​ if (tile != 0) {
​ int targetX = (tile - 1) / N;
​ int targetY = (tile - 1) % N;
​ h += abs(i - targetX) + abs(j - targetY);
​ }
​ }
​ }
​ return h;
}
void printState(Node node) {
​ for (int i = 0; i < N; i++) {
​ for (int j = 0; j < N; j++) {
​ printf("%2d ", node.state[i][j]);
​ }
​ printf("\n");
​ }
​ printf("\n");
}

int isValidMove(int x, int y) {


​ return (x >= 0 && x < N && y >= 0 && y < N);
}

void swap(Node *node, int x1, int y1, int x2, int y2) {
​ int temp = node->state[x1][y1];
​ node->state[x1][y1] = node->state[x2][y2];
​ node->state[x2][y2] = temp;
}

void expandNode(Node *currentNode) {


​ int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; // Up, Down, Left, Right
​ for (int i = 0; i < 4; i++) {
​ int newX = currentNode->emptyX + directions[i][0];
​ int newY = currentNode->emptyY + directions[i][1];
​ if (isValidMove(newX, newY)) {
​ Node newNode = *currentNode;
​ swap(&newNode, currentNode->emptyX, currentNode->emptyY, newX, newY);
​ newNode.emptyX = newX;
​ newNode.emptyY = newY;
​ newNode.cost = currentNode->cost + 1;
​ newNode.heuristic = calculateHeuristic(newNode);
​ enqueue(newNode);
​ }
​ }
}

void branchAndBound(Node startNode) {


​ enqueue(startNode);

​ while (!isQueueEmpty()) {
​ Node currentNode = dequeue();

​ if (isGoalState(currentNode)) {
​ printf("Goal state reached:\n");
​ printState(currentNode);
​ return;
​ }

​ expandNode(&currentNode);
​ }

​ printf("No solution found.\n");


}

int main() {
​ Node startNode = {
​ .state = {
​ {1, 2, 3, 4},
​ {5, 6, 0, 8},
​ {9, 10, 7, 11},
​ {13, 14, 15, 12}
​ },
​ .cost = 0,
​ .heuristic = 0,
​ .emptyX = 1,
​ .emptyY = 2
​ };

​ startNode.heuristic = calculateHeuristic(startNode);

​ printf("Initial state:\n");
​ printState(startNode);

​ branchAndBound(startNode);

​ return 0;
}

You might also like