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

Lab Fat Daa

The documents discuss various algorithms - Greedy Activity Selection, Huffman Coding, Matrix Chain Multiplication, LCSS, Maximum Subarray, Karatsuba Multiplication. The algorithms are implemented in C code with functions to find optimal solutions to problems like scheduling activities, constructing Huffman trees, multiplying matrices efficiently, finding longest common subsequence, and finding maximum sum subarrays.

Uploaded by

Talha Khan
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)
20 views

Lab Fat Daa

The documents discuss various algorithms - Greedy Activity Selection, Huffman Coding, Matrix Chain Multiplication, LCSS, Maximum Subarray, Karatsuba Multiplication. The algorithms are implemented in C code with functions to find optimal solutions to problems like scheduling activities, constructing Huffman trees, multiplying matrices efficiently, finding longest common subsequence, and finding maximum sum subarrays.

Uploaded by

Talha Khan
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/ 24

1.

Greedy Strategy: Ac vity Selec on

#include<stdio.h>
int main(){
int start[5]={1,5,12,251};
int finish[5]={10,13,23,24};
int ac vi es = sizeof(start)/sizeof(start[0]);
int i, j;
i = 0;
prin ("%d\n", i);
for (j = 1; j < ac vi es; j++){
if (start[j] >= finish[i]){
prin ("%d\n", j);
i = j;
}
}
return 0;
}

2. Huffman Coding

#include <stdio.h>
#include <stdlib.h>
#define MAX_TREE_HT 100
struct MinHeapNode {
char data;
unsigned freq;
struct MinHeapNode *le , *right;
};
struct MinHeap {
unsigned size;
unsigned capacity;
struct MinHeapNode** array;
};
struct MinHeapNode* newNode(char data, unsigned freq)
{
struct MinHeapNode* temp = (struct MinHeapNode*)malloc(
sizeof(struct MinHeapNode));
temp->le = temp->right = NULL;
temp->data = data;
temp->freq = freq;
return temp;
}
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;
}
void swapMinHeapNode(struct MinHeapNode** a,
struct MinHeapNode** b)
{

struct MinHeapNode* t = *a;


*a = *b;
*b = t;
}
void minHeapify(struct MinHeap* minHeap, int idx)
{
int smallest = idx;
int le = 2 * idx + 1;
int right = 2 * idx + 2;
if (le < minHeap->size
&& minHeap->array[le ]->freq
< minHeap->array[smallest]->freq)
smallest = le ;
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);
}
}
int isSizeOne(struct MinHeap* minHeap)
{
return (minHeap->size == 1);
}
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;
}
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;
}
void buildMinHeap(struct MinHeap* minHeap)
{
int n = minHeap->size - 1;
int i;
for (i = (n - 1) / 2; i >= 0; --i)
minHeapify(minHeap, i);
}
void printArr(int arr[], int n)
{
int i;
for (i = 0; i < n; ++i)
prin ("%d", arr[i]);
prin ("\n");
}
int isLeaf(struct MinHeapNode* root)
{
return !(root->le ) && !(root->right);
}
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;
}
struct MinHeapNode* buildHuffmanTree(char data[],
int freq[], int size)
{
struct MinHeapNode *le , *right, *top;
struct MinHeap* minHeap
= createAndBuildMinHeap(data, freq, size);
while (!isSizeOne(minHeap)) {
le = extractMin(minHeap);
right = extractMin(minHeap);
top = newNode('$', le ->freq + right->freq);
top->le = le ;
top->right = right;
insertMinHeap(minHeap, top);
}
return extractMin(minHeap);
}
void printCodes(struct MinHeapNode* root, int arr[],
int top)
{
if (root->le ) {
arr[top] = 0;
printCodes(root->le , arr, top + 1);
}
if (root->right) {
arr[top] = 1;
printCodes(root->right, arr, top + 1);
}
if (isLeaf(root)) {
prin ("%c: ", root->data);
printArr(arr, top);
}
}
void HuffmanCodes(char data[], int freq[], int size)
{
struct MinHeapNode* root
= buildHuffmanTree(data, freq, size);
int arr[MAX_TREE_HT], top = 0;
printCodes(root, arr, top);
}
int main()
{
char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
int freq[] = { 5, 9, 12, 13, 16, 45 };
int size = sizeof(arr) / sizeof(arr[0]);
HuffmanCodes(arr, freq, size);
return 0;
}

3. Matrix Chain Mul plica on


#include <limits.h>
#include <stdio.h>
int MatrixChainOrder(int p[], int n)
{
int m[n][n];
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;
}
}
}
return m[1][n - 1];
}
int main()
{
int arr[] = { 1, 2, 3, 4 };
int size = sizeof(arr) / sizeof(arr[0]);
prin ("Minimum number of mul plica ons is %d ",
MatrixChainOrder(arr, size));
getchar();
return 0;
}

4. LCSS
#include<stdio.h>
#include<string.h>
int i,j,m,n, x[20][20];
char A1[20]="BDCB",A2[20]="BACDB",b[20][20];
void sub(){
m=strlen(A1);
n=strlen(A2);
for(i=0;i<=m;i++)
x[i][0]=0;
for(i=0;i<=n;i++)
x[0][i]=0;
for(i=1;i<=m;i++)
for(j=1;j<=n;j++){
if(A1[i-1]==A2[j-1]){
x[i][j]=x[i-1][j-1]+1;
}
else if(x[i-1][j]>=x[i][j-1]){
x[i][j]=x[i-1][j];
}
else{
x[i][j]=x[i][j-1];
}
}
int index=x[m][n];
char sub[21];
sub[index]='\0';
int i=m,j=n;
while(i>0&&j>0){
if(A1[i-1]==A2[j-1]){
sub[index-1]=A1[i-1];
i--;
j--;
index--;
}
else if(x[i-1][j]>x[i][j-1])
i--;
else
j--;
}
prin ("LCS=%s\n\n\n",sub);
int k=strlen(sub);
prin ("Length=%d",k);
}
int main(){
sub();
prin ("\n");
}

5. Maximum Subarray
#include <stdio.h>
#include <limits.h>

// A u lity func on to find maximum of two integers


int max(int a, int b) {
return (a > b) ? a : b;
}

// A u lity func on to find maximum of three integers


int maxThree(int a, int b, int c) {
return max(max(a, b), c);
}

// Find the maximum possible sum in arr[] such that arr[m]


// is part of it
int maxCrossingSum(int arr[], int l, int m, int h) {
// Include elements on le of mid.
int sum = 0;
int le _sum = INT_MIN;
for (int i = m; i >= l; i--) {
sum = sum + arr[i];
if (sum > le _sum)
le _sum = sum;
}

// Include elements on right of mid


sum = 0;
int right_sum = INT_MIN;
for (int i = m; i <= h; i++) {
sum = sum + arr[i];
if (sum > right_sum)
right_sum = sum;
}

// Return sum of elements on le and right of mid


// returning only le _sum + right_sum will fail for
// [-2, 1]
return maxThree(le _sum + right_sum - arr[m], le _sum, right_sum);
}

// Returns sum of maximum sum subarray in aa[l..h]


int maxSubArraySum(int arr[], int l, int h) {
// Invalid Range: low is greater than high
if (l > h)
return INT_MIN;
// Base Case: Only one element
if (l == h)
return arr[l];

// Find middle point


int m = (l + h) / 2;

/* Return maximum of following three possible cases


a) Maximum subarray sum in le half
b) Maximum subarray sum in right half
c) Maximum subarray sum such that the subarray
crosses the midpoint */
return maxThree(maxSubArraySum(arr, l, m - 1),
maxSubArraySum(arr, m + 1, h),
maxCrossingSum(arr, l, m, h));
}

/*Driver program to test maxSubArraySum*/


int main() {
int arr[] = { 2, 3, 4, 5, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
int max_sum = maxSubArraySum(arr, 0, n - 1);
prin ("Maximum con guous sum is %d\n", max_sum);
return 0;
}

6. Karatsuba Algorithm
#include <stdio.h>
#include <math.h>

int digits(long number) {


if (number == 0) {
return 1;
}
return (int) (log10(number) + 1);
}

long pow10(int n) {
long result = 1;
for (int i = 0; i < n; i++) {
result *= 10;
}
return result;
}

void divideNumberInto2Parts(long number, int n, long *le Part, long *rightPart) {


long divideBy = pow10((int) ceil((float)n/2));
*rightPart = number % divideBy;
*le Part = (number - *rightPart) / divideBy;
}

long mul ply(long X, long Y) {


int xn = digits(X);
int yn = digits(Y);
int n = fmax(xn, yn);

if (n == 1) {
return X * Y;
}

long a, b, c, d, ac, bd, adPluscb, k;

divideNumberInto2Parts(X, n, &a, &b);


divideNumberInto2Parts(Y, n, &c, &d);

ac = mul ply(a, c);


bd = mul ply(b, d);
adPluscb = mul ply(a + b, c + d) - ac - bd;

k = pow10(n) * ac + pow10((int) ceil((float)n/2)) * adPluscb + bd;


return k;
}

int main() {
long X = 12;
long Y = 4;

prin ("%ld\n", mul ply(X, Y));

return 0;
}

7. Backtracking Nqueens

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool isSafe(int **board, int row, int col, int n) {
for (int i = 0; i < col; i++) {
if (board[row][i]) {
return false;
}
}
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (board[i][j]) {
return false;
}
}
for (int i = row, j = col; j >= 0 && i < n; i++, j--) {
if (board[i][j]) {
return false;
}
}
return true;
}
bool solveNQueens(int **board, int col, int n) {
if (col == n) {
return true;
}
for (int i = 0; i < n; i++) {
if (isSafe(board, i, col, n)) {
board[i][col] = 1;
if (solveNQueens(board, col + 1, n)) {
return true;
}
board[i][col] = 0;
}
}
return false;
}
void printBoard(int **board, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
prin ("%d ", board[i][j]);
}
prin ("\n");
}
}
int main() {
int n;
prin ("Enter the number of queens: ");
scanf("%d", &n);
int **board = malloc(n * sizeof(int *));
for (int i = 0; i < n; i++) {
board[i] = malloc(n * sizeof(int));
for (int j = 0; j < n; j++) {
board[i][j] = 0;
}
}
if (solveNQueens(board, 0, n)) {
printBoard(board, n);
} else {
prin ("No solu on exists.\n");
}
for (int i = 0; i < n; i++) {
free(board[i]);
}
free(board);
return 0;
}

8. Branch and Bound Job Selec on


#include<stdio.h>
#include<stdlib.h>
#include<math.h>
struct Job{
int profit;
int deadline;
int me;
};
int compareJobs(const void*a,const void*b){
struct Job*job1=(struct Job*)a;
struct Job*job2=(struct Job*)b;
double profitPerUnitTime1=(double)job1->profit/job1-> me;
double profitPerUnitTime2=(double)job2->profit/job2-> me;
if(profitPerUnitTime1<profitPerUnitTime2){
return 1;
}
else if(profitPerUnitTime1>profitPerUnitTime2){
return -1;
}else{
return 0;
}
}
int maxProfit(struct Job jobs[],int n,int currProfit,int currTime, int currDeadline){
qsort(jobs,n,sizeof(struct Job),compareJobs);
int max_Profit=currProfit;
if(n>0){
if(currTime+jobs[0]. me<=jobs[0].deadline){
int newProfit=currProfit+jobs[0].profit;
int newTime=currTime+jobs[0]. me;
int newDeadline=currDeadline;
if(newTime>currDeadline)
{
newDeadline=newTime;
}
max_Profit=fmax(max_Profit,maxProfit(jobs+1,n-
1,newProfit,newTime,newDeadline));
}
max_Profit=fmax(max_Profit,maxProfit(jobs+1,n-1,currProfit,currTime,currDeadline));
}
return max_Profit;
}
int main(){
struct Job jobs[]={
{5,1,1},
{10,3,2},
{6,2,1},
{3,1,1}
};
int n=sizeof(jobs)/sizeof(jobs[0]);
int max_Profit=maxProfit(jobs,n,0,0,0);
prin ("max profit=%d\n",max_Profit);
}

9. KMP
#include<stdio.h>
#include<string.h>
void x(char *pat,int M,int *lps)
{
int len=0;
int i=1;
lps[0]=0;
while(i<M)
{
if(pat[i]==pat[len])
{
len++;
lps[i]=len;
i++;
}
else
{
if(len!=0)
{
len=lps[len-1];
}

else{
lps[i]=0;
i++;

}
}
}
}
void y(char *pat,char *txt)
{
int M=strlen(pat);
int N=strlen(txt);
int lps[M];
x(pat,M,lps);
int i=0;
int j=0;
while(i<N)
{
if(pat[j]==txt[i]){
j++;
i++;
}
if(j==M){
prin ("The match is found:%d-%d\n",i-j+1,i);
j=lps[j-1];
}else if(i<N && pat[j]!=txt[i]){
if(j!=0)
j=lps[j-1];
else
i=i+1;
}
}
}
int main()
{
char txt[100]="aaabbbaba",pat[100]="baba";
y(pat,txt);
}
10. Rabin Karp
#include <stdio.h>
#include <string.h>

#define d 256 // The number of possible characters in the input alphabet

void rabinKarp(char* pa ern, char* text, int q) {


int pa ernLength = strlen(pa ern);
int textLength = strlen(text);
int pa ernHash = 0; // Hash value for the pa ern
int textHash = 0; // Hash value for the current window in the text
int h = 1;

// Calculate the hash value of the pa ern and the ini al hash value of the first window in the text
for (int i = 0; i < pa ernLength; i++) {
pa ernHash = (d * pa ernHash + pa ern[i]) % q;
textHash = (d * textHash + text[i]) % q;
}

// Calculate h as d^(m-1) where m is the length of the pa ern


for (int i = 0; i < pa ernLength - 1; i++) {
h = (h * d) % q;
}

// Slide the pa ern over the text one by one and compare their hash values
for (int i = 0; i <= textLength - pa ernLength; i++) {
// If the hash values match, compare the pa ern and the current window character by character
if (pa ernHash == textHash) {
int j;
for (j = 0; j < pa ernLength; j++) {
if (text[i+j] != pa ern[j])
break;
}
if (j == pa ernLength)
prin ("Pa ern found at index %d\n", i);
}

// Calculate the hash value for the next window in the text
if (i < textLength - pa ernLength) {
textHash = (d * (textHash - text[i] * h) + text[i+pa ernLength]) % q;
if (textHash < 0) // In case we get a nega ve hash value
textHash = (textHash + q);
}
}
}

int main() {
char text[] = "ABABDABACDABABCABAB";
char pa ern[] = "ABABCABAB";
int q = 101; // A prime number
rabinKarp(pa ern, text, q);
return 0;
}

11. Floyd Warshall


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

#define V 4

// A func on to print the solu on matrix


void printSolu on(int dist[][V])
{
prin ("The following matrix shows the shortest distances"
" between every pair of ver ces \n");
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
if (dist[i][j] == INT_MAX)
prin ("INF ");
else
prin ("%d ", dist[i][j]);
}
prin ("\n");
}
}

// Solves the all-pairs shortest path problem using Floyd Warshall algorithm
void floydWarshall (int graph[][V])
{
int dist[V][V], i, j, k;

// Ini alize the solu on matrix same as input graph matrix.


for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
dist[i][j] = graph[i][j];

// k is an intermediate vertex between i and j.


for (k = 0; k < V; k++)
{
// Pick all ver ces as source one by one
for (i = 0; i < V; i++)
{
// Pick all ver ces as des na on for the
// above picked source
for (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] != INT_MAX &&
dist[k][j] != INT_MAX &&
dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}

printSolu on(dist);
}

// Driver program to test above func on


int main()
{
int graph[V][V] = { {0, 5, INT_MAX, 10},
{INT_MAX, 0, 3, INT_MAX},
{INT_MAX, INT_MAX, 0, 1},
{INT_MAX, INT_MAX, INT_MAX, 0}
};

// Print the solu on


floydWarshall(graph);
return 0;
}

12. FORD FULKERSON


#include <stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<string.h>
#include<limits.h>
#define V 6
bool bfs(int residual_graph[V][V],int source, int sink,int parent[]){
bool visited[V];
memset(visited,false,sizeof(visited));
visited[source]=true;
int queue[V],front=0,rear=0;
queue[rear++]=source;
parent[source]=-1;
while(front!=rear){
int u=queue[front++];
for(int v=0;v<V;v++){
if(!visited[v] && residual_graph[u][v]>0 ){
visited[v]=true;
parent[v]=u;
queue[rear++]=v;
}
}
}
return visited[sink];
}
int ford_fulkerson(int graph[V][V],int source,int sink){
int residual_graph[V][V];
memcpy(residual_graph,graph,sizeof(residual_graph));
int parent[V];
int max_flow=0;
while(bfs(residual_graph,source,sink,parent)){
int path_flow=INT_MAX;
for(int v=sink;v!=source;v=parent[v]){
int u=parent[v];
path_flow=path_flow<residual_graph[u][v]?path_flow:residual_graph[u][v];
}
for(int v=sink;v!=source;v=parent[v]){
int u=parent[v];
residual_graph[u][v]-=path_flow;
residual_graph[v][u]+=path_flow;
}
max_flow+=path_flow;
}
return max_flow;
}
int main(){
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}
};
int source=0;
int sink=V-1;
int max_flow=ford_fulkerson(graph,source,sink);
prin ("The maximum possible flow is %d\n",max_flow);
}

13. EDMONDS KARP


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

#define N 6 // Number of nodes in the graph

int bfs(int graph[N][N], int s, int t, int parent[]) {


int visited[N] = {0};
int queue[N];
int front = 0, rear = 0;
queue[rear++] = s;
visited[s] = 1;
parent[s] = -1;

while (front < rear) {


int u = queue[front++];
for (int v = 0; v < N; v++) {
if (!visited[v] && graph[u][v] > 0) {
queue[rear++] = v;
visited[v] = 1;
parent[v] = u;
}
}
}

return visited[t];
}

int edmondsKarp(int graph[N][N], int s, int t) {


int u, v;
int maxFlow = 0;
int parent[N];

while (bfs(graph, s, t, parent)) {


int pathFlow = INT_MAX;
for (v = t; v != s; v = parent[v]) {
u = parent[v];
pathFlow = pathFlow < graph[u][v] ? pathFlow : graph[u][v];
}
for (v = t; v != s; v = parent[v]) {
u = parent[v];
graph[u][v] -= pathFlow;
graph[v][u] += pathFlow;
}
maxFlow += pathFlow;
}

return maxFlow;
}

int main() {
int graph[N][N] = { {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}
};

prin ("Maximum flow is %d\n", edmondsKarp(graph, 0, 5));

return 0;
}

14a. Graham’s scan convex hull finding algorithm

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

typedef struct {
int x, y;
} Point;

int orienta on(Point p, Point q, Point r) {


int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
if (val == 0) return 0;
return (val > 0) ? 1 : 2;
}

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


Point t = *a;
*a = *b;
*b = t;
}

void sort_points(Point* points, int n) {


int i, j, min;
for (i = 0; i < n - 1; i++) {
min = i;
for (j = i + 1; j < n; j++)
if (points[j].y < points[min].y || (points[j].y == points[min].y && points[j].x < points[min].x))
min = j;
swap(&points[min], &points[i]);
}
}

void convex_hull(Point* points, int n) {


if (n < 3) return;
int i, j, k;
Point hull[n];
int top = 0;
sort_points(points, n);
hull[top++] = points[0];
hull[top++] = points[1];
for (i = 2; i < n; i++) {
while (top >= 2 && orienta on(hull[top - 2], hull[top - 1], points[i]) != 2)
top--;
hull[top++] = points[i];
}
for (i = 0; i < top; i++)
prin ("(%d,%d)\n", hull[i].x, hull[i].y);
}

int main() {
Point points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}};
int n = sizeof(points)/sizeof(points[0]);
convex_hull(points, n);
return 0;
}

14b. Jarvis’ March convex hull finding algorithm


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

typedef struct {
int x, y;
} Point;

int orienta on(Point p, Point q, Point r) {


int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
if (val == 0) return 0;
return (val > 0) ? 1 : 2;
}

void convex_hull(Point* points, int n) {


if (n < 3) return;
int i, j, le most = 0;
for (i = 1; i < n; i++)
if (points[i].x < points[le most].x)
le most = i;
int p = le most, q;
do {
prin ("(%d,%d)\n", points[p].x, points[p].y);
q = (p + 1) % n;
for (i = 0; i < n; i++)
if (orienta on(points[p], points[i], points[q]) == 2)
q = i;
p = q;
} while (p != le most);
}

int main() {
Point points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}};
int n = sizeof(points)/sizeof(points[0]);
convex_hull(points, n);
return 0;
}

15. Randomized quick sort algorithm

#include <stdio.h>
#include <stdlib.h>
#include < me.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int par on(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j <= high - 1; j++) {
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i+1], &arr[high]);
return (i+1);
}
int randomPar on(int arr[], int low, int high) {
srand( me(NULL));
int random = low + rand() % (high - low);
swap(&arr[random], &arr[high]);
return par on(arr, low, high);
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = randomPar on(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int main() {
int arr[] = {67, 0, 23, 11, 1, 21, 65, 63, 50, 33};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n-1);
for (int i = 0; i < n; i++) {
prin ("%d ", arr[i]);
}
return 0;
}

16. Randomised Hiring Problem

#include <stdio.h>

int main() {
int id[] = {0, 1, 2, 3}; // candidate IDs
int rank[] = {5, 7, 9, 10}; // candidate ranks
int current_rank = -1; // current assistant rank
int num_candidates = sizeof(rank) / sizeof(rank[0]); // number of candidates
int ci = 10; // cost to interview a candidate
int ch = 100; // cost to hire a candidate
int hire;

// Iterate through all candidates


for (int i = 0; i < num_candidates; i++) {
// Hire the first candidate
if (i == 0) {
current_rank = rank[i];
}
else if (rank[i] > current_rank) {
current_rank = rank[i];
}
}
prin ("The person with rank %d is hired",current_rank);

return 0;
}

17. Frac onal Knapsack


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

struct Item {
int value;
int weight;
};

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


struct Item *item1 = (struct Item *)a;
struct Item *item2 = (struct Item *)b;
double ra o1 = (double)item1->value / item1->weight;
double ra o2 = (double)item2->value / item2->weight;
if (ra o1 < ra o2) {
return 1;
} else if (ra o1 > ra o2) {
return -1;
} else {
return 0;
}
}

double frac onalKnapsack(int capacity, struct Item *items, int n) {


qsort(items, n, sizeof(struct Item), compare);
double totalValue = 0;
int i;
for (i = 0; i < n; i++) {
if (capacity == 0) {
return totalValue;
}
if (items[i].weight <= capacity) {
capacity -= items[i].weight;
totalValue += items[i].value;
} else {
totalValue += ((double)capacity / items[i].weight) * items[i].value;
break;
}
}
return totalValue;
}

int main() {
struct Item items[] = {{10, 2}, {5, 3}, {15, 5},{7,7},{6,1},{18,4},{3,1}};
int capacity = 15;
int n = sizeof(items) / sizeof(items[0]);
double result = frac onalKnapsack(capacity, items, n);
prin ("Maximum value in Knapsack = %.2f", result);
return 0;
}

18. Subset Sum


#include <stdio.h>
#include <stdbool.h>

bool subsetSum(int set[], int n, int sum)


{
bool subset[n+1][sum+1];

// Ini alize first column as true. It's possible to make a sum of 0 with any number of elements
for (int i = 0; i <= n; i++)
subset[i][0] = true;

// Ini alize first row as false. It's not possible to make a non-zero sum with an empty set
for (int i = 1; i <= sum; i++)
subset[0][i] = false;

// Fill the subset table


for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= sum; j++)
{
if (j < set[i-1])
subset[i][j] = subset[i-1][j];
else
subset[i][j] = subset[i-1][j] || subset[i-1][j-set[i-1]];
}
}
// The last cell of the table contains the solu on
return subset[n][sum];
}

int main()
{
int set[] = {3, 34, 4, 12, 5, 2};
int n = sizeof(set)/sizeof(set[0]);
int sum = 9;

if (subsetSum(set, n, sum))
prin ("There exists a subset of the given set with the given sum\n");
else
prin ("There does not exist a subset of the given set with the given sum\n");

return 0;
}

19. Naïve
#include<stdio.h>
#include<string.h>
int main()
{
char text[100]="aaabbbaba",pa ern[100]="baba";
int n=strlen(text);
int m=strlen(pa ern);
for(int i=0;i<=n-m;i++){
int j;
for(j=0;j<m;j++){
if(text[i+j]!=pa ern[j]){
break;
}
}
if(j==m){
prin ("The match is found:%d-%d\n",i+1,i+m);
}
}
}

You might also like