You are on page 1of 26

1.Binary search using iterative method.

#include <stdio.h>

int binary_search(int arr[], int n, int x) {

int low = 0, high = n - 1, mid;

while (low <= high) {

mid = (low + high) / 2;

if (arr[mid] == x) {

return mid;

} else if (arr[mid] < x) {

low = mid + 1;

} else {

high = mid - 1;

return -1; // if x not found in arr

int main() {

int arr[100], n, x, index;

printf("Enter the number of elements in the array: ");

scanf("%d", &n);

printf("Enter the elements in the sorted array:\n");

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

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

}
printf("Enter the element to be searched: ");

scanf("%d", &x);

index = binary_search(arr, n, x);

if (index == -1) {

printf("Element not found in the array.\n");

} else {

printf("Element found at index %d.\n", index);

return 0;

2.Binary search using recursive method.

#include <stdio.h>

int binary_search(int arr[], int low, int high, int x) {

if (low > high) {

return -1; // if x not found in arr

int mid = (low + high) / 2;

if (arr[mid] == x) {

return mid;

} else if (arr[mid] < x) {

return binary_search(arr, mid + 1, high, x);

} else {
return binary_search(arr, low, mid - 1, x);

int main() {

int arr[100], n, x, index;

printf("Enter the number of elements in the array: ");

scanf("%d", &n);

printf("Enter the elements in the sorted array:\n");

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

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

printf("Enter the element to be searched: ");

scanf("%d", &x);

index = binary_search(arr, 0, n - 1, x);

if (index == -1) {

printf("Element not found in the array.\n");

} else {

printf("Element found at index %d.\n", index);

return 0;

}
3.Insertion Sort

#include <stdio.h>

void insertion_sort(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;

int main() {

int arr[100], n;

printf("Enter the number of elements in the array: ");

scanf("%d", &n);

printf("Enter the elements of the array:\n");

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

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

insertion_sort(arr, n);
printf("Sorted array in ascending order:\n");

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

printf("%d ", arr[i]);

return 0;

4.Merge Sort

#include <stdio.h>

void merge(int arr[], int left[], int left_size, int right[], int right_size) {

int i = 0, j = 0, k = 0;

while (i < left_size && j < right_size) {

if (left[i] <= right[j]) {

arr[k++] = left[i++];

} else {

arr[k++] = right[j++];

while (i < left_size) {

arr[k++] = left[i++];

while (j < right_size) {

arr[k++] = right[j++];

}
void merge_sort(int arr[], int n) {

if (n < 2) {

return;

int mid = n / 2;

int left[mid], right[n - mid];

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

left[i] = arr[i];

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

right[i - mid] = arr[i];

merge_sort(left, mid);

merge_sort(right, n - mid);

merge(arr, left, mid, right, n - mid);

int main() {

int arr[100], n;

printf("Enter the number of elements in the array: ");

scanf("%d", &n);

printf("Enter the elements of the array:\n");

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


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

merge_sort(arr, n);

printf("Sorted array in ascending order:\n");

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

printf("%d ", arr[i]);

return 0;

5.Quick Sort

#include <stdio.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 quick_sort(int arr[], int low, int high) {

if (low < high) {

int pi = partition(arr, low, high);

quick_sort(arr, low, pi - 1);

quick_sort(arr, pi + 1, high);

int main() {

int arr[100], n;

printf("Enter the number of elements in the array: ");

scanf("%d", &n);

printf("Enter the elements of the array:\n");

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

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

quick_sort(arr, 0, n - 1);

printf("Sorted array in ascending order:\n");

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

printf("%d ", arr[i]);


}

return 0;

6.Heap Sort.

#include <stdio.h>

void heapify(int arr[], int n, int i) {

int largest = i;

int left_child = 2 * i + 1;

int right_child = 2 * i + 2;

if (left_child < n && arr[left_child] > arr[largest])

largest = left_child;

if (right_child < n && arr[right_child] > arr[largest])

largest = right_child;

if (largest != i) {

int temp = arr[i];

arr[i] = arr[largest];

arr[largest] = temp;

heapify(arr, n, largest);

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

for (int i = n / 2 - 1; i >= 0; i--)

heapify(arr, n, i);
for (int i = n - 1; i >= 0; i--) {

int temp = arr[0];

arr[0] = arr[i];

arr[i] = temp;

heapify(arr, i, 0);

int main() {

int arr[100], n;

printf("Enter the number of elements in the array: ");

scanf("%d", &n);

printf("Enter the elements of the array:\n");

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

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

heap_sort(arr, n);

printf("Sorted array in ascending order:\n");

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

printf("%d ", arr[i]);

return 0;

}
7.Job Sequencing with Deadline.

#include <stdio.h>

struct job {

int id;

int profit;

int deadline;

};

void job_sequence(struct job arr[], int n) {

int i, j;

int max_deadline = arr[0].deadline;

for (i = 1; i < n; i++) {

if (arr[i].deadline > max_deadline)

max_deadline = arr[i].deadline;

int slots[max_deadline];

for (i = 0; i < max_deadline; i++) {

slots[i] = -1;

int total_profit = 0;

printf("Job sequence: ");

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

for (j = arr[i].deadline - 1; j >= 0; j--) {

if (slots[j] == -1) {

slots[j] = arr[i].id;

total_profit += arr[i].profit;

break;
}

if (j >= 0)

printf("%d ", arr[i].id);

printf("\nTotal profit: %d\n", total_profit);

printf("Selected jobs: ");

for (i = 0; i < max_deadline; i++) {

if (slots[i] != -1)

printf("%d ", slots[i]);

printf("\n");

int main() {

int n, i;

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

scanf("%d", &n);

struct job arr[n];

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

printf("Enter profit and deadline for job %d: ", i+1);

scanf("%d%d", &arr[i].profit, &arr[i].deadline);

arr[i].id = i+1;

// sort jobs in descending order of profits

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


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

if (arr[j].profit < arr[j+1].profit) {

struct job temp = arr[j];

arr[j] = arr[j+1];

arr[j+1] = temp;

job_sequence(arr, n);

return 0;

8.Graph colouring.

#include <stdio.h>

#include <stdlib.h>

#define MAX_VERTICES 100

#define MAX_DEGREE 100

// Vertex struct

typedef struct {

int id;

int degree;

int color;

int adj[MAX_DEGREE];

} Vertex;

// Graph struct

typedef struct {
int num_vertices;

int num_edges;

Vertex vertices[MAX_VERTICES];

} Graph;

// Add an edge to the graph

void add_edge(Graph* graph, int src, int dest) {

int degree = graph->vertices[src].degree;

graph->vertices[src].adj[degree] = dest;

graph->vertices[src].degree++;

degree = graph->vertices[dest].degree;

graph->vertices[dest].adj[degree] = src;

graph->vertices[dest].degree++;

// Print the graph

void print_graph(Graph* graph) {

printf("Graph:\n");

for (int i = 0; i < graph->num_vertices; i++) {

printf("%d: ", graph->vertices[i].id);

for (int j = 0; j < graph->vertices[i].degree; j++) {

printf("%d ", graph->vertices[i].adj[j]);

printf("\n");

// Color the graph

void color_graph(Graph* graph) {

int used_colors[MAX_VERTICES] = {0};


for (int i = 0; i < graph->num_vertices; i++) {

Vertex* vertex = &graph->vertices[i];

int available_colors[MAX_VERTICES] = {0};

for (int j = 0; j < vertex->degree; j++) {

int adj_vertex_id = vertex->adj[j];

int adj_vertex_color = graph->vertices[adj_vertex_id].color;

if (adj_vertex_color != -1) {

used_colors[adj_vertex_color] = 1;

int color = 0;

while (used_colors[color]) {

color++;

vertex->color = color;

for (int j = 0; j < vertex->degree; j++) {

int adj_vertex_id = vertex->adj[j];

int adj_vertex_color = graph->vertices[adj_vertex_id].color;

if (adj_vertex_color != -1) {

used_colors[adj_vertex_color] = 0;

// Print the vertex colors

void print_colors(Graph* graph) {

printf("Vertex colors:\n");

for (int i = 0; i < graph->num_vertices; i++) {

printf("%d: %d\n", graph->vertices[i].id, graph->vertices[i].color);

}
}

int main() {

int num_vertices, num_edges;

Graph graph;

// Read in the number of vertices and edges

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

scanf("%d", &num_vertices);

graph.num_vertices = num_vertices;

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

scanf("%d", &num_edges);

graph.num_edges = num_edges;

// Initialize the graph

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

Vertex vertex = {i, 0, -1};

graph.vertices[i] = vertex;

// Read in the edges

// Read in the edges

printf("Enter the edges as pairs of vertices (e.g. 0 1):\n");

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

int src, dest;

scanf("%d %d", &src, &dest);

add_edge(&graph, src, dest);

}
// Print the graph

print_graph(&graph);

// Color the graph

color_graph(&graph);

// Print the vertex colors

print_colors(&graph);

return 0;

9.KMP Algo.

#include <stdio.h>

#include <string.h>

void kmp(char* text, char* pattern) {

int n = strlen(text);

int m = strlen(pattern);

int i, j;

// Compute the prefix function

int pi[m];

pi[0] = 0;

for (i = 1, j = 0; i < m; i++) {

while (j > 0 && pattern[i] != pattern[j]) {

j = pi[j - 1];

if (pattern[i] == pattern[j]) {

j++;

}
pi[i] = j;

// Use the prefix function to search for the pattern in the text

for (i = 0, j = 0; i < n; i++) {

while (j > 0 && text[i] != pattern[j]) {

j = pi[j - 1];

if (text[i] == pattern[j]) {

j++;

if (j == m) {

printf("Pattern found at index %d\n", i - m + 1);

j = pi[j - 1];

int main() {

char text[1000];

char pattern[1000];

printf("Enter text: ");

fgets(text, sizeof(text), stdin);

printf("Enter pattern: ");

fgets(pattern, sizeof(pattern), stdin);

// Remove newline characters from input

text[strcspn(text, "\n")] = '\0';

pattern[strcspn(pattern, "\n")] = '\0';


kmp(text, pattern);

return 0;

10.Matrix Chain Multiplication.

#include <stdio.h>

#include <limits.h>

#define MAX_SIZE 100

void matrixChainOrder(int p[], int n, int m[MAX_SIZE][MAX_SIZE], int s[MAX_SIZE][MAX_SIZE]) {

int i, j, k, l, q;

for (i = 1; i <= n; i++) {

m[i][i] = 0;

for (l = 2; l <= n; l++) {

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

j = i + l - 1;

m[i][j] = INT_MAX;

for (k = i; k <= j - 1; k++) {

q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];

if (q < m[i][j]) {

m[i][j] = q;

s[i][j] = k;

}
void printOptimalParens(int s[MAX_SIZE][MAX_SIZE], int i, int j) {

if (i == j) {

printf("A%d", i);

} else {

printf("(");

printOptimalParens(s, i, s[i][j]);

printOptimalParens(s, s[i][j]+1, j);

printf(")");

int main() {

int n, p[MAX_SIZE];

int m[MAX_SIZE][MAX_SIZE], s[MAX_SIZE][MAX_SIZE];

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

scanf("%d", &n);

printf("Enter the dimensions of the matrices:\n");

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

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

matrixChainOrder(p, n, m, s);

printf("Optimal Parenthesization: ");

printOptimalParens(s, 1, n);

printf("\nMinimum number of scalar multiplications: %d\n", m[1][n]);

return 0;

}
11.Fractional Knapsack.

#include <stdio.h>

// Structure to represent an item and its properties

struct Item {

int value; // Value of the item

int weight; // Weight of the item

};

// Function to calculate the maximum of two integers

int max(int a, int b) {

return (a > b) ? a : b;

// Function to calculate the maximum value that can be obtained

// by filling the knapsack with items

float fractionalKnapsack(int W, struct Item arr[], int n, int selected[]) {

// Calculate the ratio of value to weight for each item

float ratio[n];

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

ratio[i] = (float) arr[i].value / arr[i].weight;

// Sort the items based on their ratio

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

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

if (ratio[j] < ratio[j+1]) {

float temp = ratio[j];

ratio[j] = ratio[j+1];

ratio[j+1] = temp;
struct Item temp_item = arr[j];

arr[j] = arr[j+1];

arr[j+1] = temp_item;

// Fill the knapsack with items in descending order of their ratio

int current_weight = 0;

float max_value = 0.0;

int i = 0;

while (current_weight < W && i < n) {

// If the item can be added completely, add it

if (current_weight + arr[i].weight <= W) {

selected[i] = arr[i].weight;

current_weight += arr[i].weight;

max_value += arr[i].value;

// If the item can't be added completely, add a fraction of it

else {

int remaining_weight = W - current_weight;

selected[i] = remaining_weight;

max_value += remaining_weight * ratio[i];

break;

i++;

// Return the maximum value that can be obtained

return max_value;
}

// Main function to take user input and test the fractional knapsack function

int main() {

int n, W;

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

scanf("%d", &n);

printf("Enter the maximum weight of the knapsack: ");

scanf("%d", &W);

// Create an array of items and take input from the user

struct Item arr[n];

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

printf("Enter the value and weight of item %d: ", i+1);

scanf("%d %d", &arr[i].value, &arr[i].weight);

int selected[n];

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

selected[i] = 0;

// Call the fractional knapsack function and print the result

float result = fractionalKnapsack(W, arr, n, selected);

printf("The maximum value that can be obtained is: %.2f\n", result);

printf("The selected items are: ");

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

if (selected[i] != 0) {

printf("%d (%d) ", i+1);

}
}

return 0;

12.0/1 Knapsack

#include<stdio.h>

int w[10],p[10],v[10][10],n,i,j,cap,x[10]= {0};

int max(int i,int j) {

return ((i>j)?i:j);

int knap(int i,int j) {

int value;

if(v[i][j]<0) {

if(j<w[i])

value=knap(i-1,j); else

value=max(knap(i-1,j),p[i]+knap(i-1,j-w[i]));

v[i][j]=value;

return(v[i][j]);

int main() {

int profit,count=0;

printf("\nEnter the number of elements\n");

scanf("%d",&n);

printf("Enter the profit and weights of the elements\n");

for (i=1;i<=n;i++) {

printf("For item no %d\n",i);

scanf("%d%d",&p[i],&w[i]);

printf("\nEnter the capacity \n");

scanf("%d",&cap);
for (i=0;i<=n;i++)

for (j=0;j<=cap;j++)

if((i==0)||(j==0))

v[i][j]=0; else

v[i][j]=-1;

profit=knap(n,cap);

i=n;

j=cap;

while(j!=0&&i!=0) {

if(v[i][j]!=v[i-1][j]) {

x[i]=1;

j=j-w[i];

i--;

} else

i--;

printf("Items included are\n");

printf("Sl.no\tweight\tprofit\n");

for (i=1;i<=n;i++)

if(x[i])

printf("%d\t%d\t%d\n",++count,w[i],p[i]);

printf("Total profit = %d\n",profit);

You might also like