You are on page 1of 19

Q1.

We have learned Quick Sort Algorithm in which first element of each subArray was
taken as pivot element but if we want to take pivot element randomly i.e. any element at any
index may become pivot then suggest modification in our Quick sort Algorithm and/or
partition Algorithm. Implement your suggestions to see results.

#include<stdio.h>

void quicksort(int number[25],int first,int last){

int i, j, pivot, temp;

if(first<last){

pivot=first;

i=first;

j=last;

while(i<j){

while(number[i]<=number[pivot]&&i<last)

i++;

while(number[j]>number[pivot])

j--;

if(i<j){

temp=number[i];

number[i]=number[j];

number[j]=temp;

temp=number[pivot];

number[pivot]=number[j];

number[j]=temp;

quicksort(number,first,j-1);

quicksort(number,j+1,last);

}
}

int main(){

int i, count, number[25];

printf("How many elements are u going to enter?: ");

scanf("%d",&count);

printf("Enter %d elements: ", count);

for(i=0;i<count;i++)

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

quicksort(number,0,count-1);

printf("Order of Sorted elements: ");

for(i=0;i<count;i++)

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

return 0;

Q2 WAP to implement longest common subsequence using dynamic programming

#include <stdio.h>

#include <string.h>

int i, j, m, n, LCS_table[20][20];

char S1[20] = "abaaba", S2[20] = "babbab", b[20][20];

void lcsAlgo() {

m = strlen(S1);

n = strlen(S2);

// Filling 0's in the matrix


for (i = 0; i <= m; i++)

LCS_table[i][0] = 0;

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

LCS_table[0][i] = 0;

// Creating the mtrix in bottom-up way

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

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

if (S1[i - 1] == S2[j - 1]) {

LCS_table[i][j] = LCS_table[i - 1][j - 1] + 1;

} else if (LCS_table[i - 1][j] >= LCS_table[i][j - 1]) {

LCS_table[i][j] = LCS_table[i - 1][j];

} else {

LCS_table[i][j] = LCS_table[i][j - 1];

int index = LCS_table[m][n];

char lcsAlgo[index + 1];

lcsAlgo[index] = '\0';

int i = m, j = n;

while (i > 0 && j > 0) {

if (S1[i - 1] == S2[j - 1]) {

lcsAlgo[index - 1] = S1[i - 1];

i--;

j--;

index--;
}

else if (LCS_table[i - 1][j] > LCS_table[i][j - 1])

i--;

else

j--;

// Printing the sub sequences

printf("S1 : %s \nS2 : %s \n", S1, S2);

printf("LCS: %s", lcsAlgo);

int main() {

lcsAlgo();

printf("\n");

Q3 WAP to implement MCM (Matrics chain Multiplication) using dynamic programming

#include <stdio.h>

int MatrixChainMultuplication(int arr[], int n) {

int minMul[n][n];

int j, q;

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


minMul[i][i] = 0;

for (int L = 2; L < n; L++) {

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

j = i + L - 1;

minMul[i][j] = 99999999;

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

q = minMul[i][k] + minMul[k + 1][j] + arr[i - 1] * arr[k] * arr[j];

if (q < minMul[i][j])

minMul[i][j] = q;

return minMul[1][n - 1];

int main(){

int arr[] = {3, 4, 5, 6, 7, 8};

int size = sizeof(arr) / sizeof(arr[0]);

printf("Minimum number of multiplications required for the matrices multiplication is %d


", MatrixChainMultuplication(arr, size));

getchar();

return 0;

}
Q5 WAP to implement sum of subset algorithms using Backtracking

#include <stdio.h>

#include <stdlib.h>

static int total_nodes;

void printValues(int A[], int size){

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

printf("%*d", 5, A[i]);

printf("\n");

void subset_sum(int s[], int t[], int s_size, int t_size, int sum, int ite, int const target_sum){

total_nodes++;

if (target_sum == sum) {

printValues(t, t_size);

subset_sum(s, t, s_size, t_size - 1, sum - s[ite], ite + 1, target_sum);

return;

else {

for (int i = ite; i < s_size; i++) {

t[t_size] = s[i];

subset_sum(s, t, s_size, t_size + 1, sum + s[i], i + 1, target_sum);

void generateSubsets(int s[], int size, int target_sum){

int* tuplet_vector = (int*)malloc(size * sizeof(int));


subset_sum(s, tuplet_vector, size, 0, 0, 0, target_sum);

free(tuplet_vector);

int main(){

int set[] = { 5, 6, 12 , 54, 2 , 20 , 15 };

int size = sizeof(set) / sizeof(set[0]);

printf("The set is ");

printValues(set , size);

generateSubsets(set, size, 25);

printf("Total Nodes generated %d\n", total_nodes);

return 0;

Q6 WAP to implement binary knapsack algorithms using Backtracking

#include <stdio.h>

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

int knapSack(int W, int wt[], int val[], int n)

if (n == 0 || W == 0)

return 0;
if (wt[n - 1] > W)

return knapSack(W, wt, val, n - 1);

else

return max(

val[n - 1]

+ knapSack(W - wt[n - 1], wt, val, n - 1),

knapSack(W, wt, val, n - 1));

int main()

int val[] = { 60, 100, 120 };

int wt[] = { 10, 20, 30 };

int W = 50;

int n = sizeof(val) / sizeof(val[0]);

printf("%d", knapSack(W, wt, val, n));

return 0;

}
Q8 WAP to implement KMP - Knuth-Morris-Pratt Pattern Matching Algorithm.

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

void computeLPSArray(char *pat, int M, int *lps);

void KMPSearch(char *pat, char *txt) {

int M = strlen(pat);

int N = strlen(txt);

// create lps[] that will hold the longest prefix suffix values for pattern

int *lps = (int *) malloc(sizeof(int) * M);

int j = 0; // index for pat[]

// Preprocess the pattern (calculate lps[] array)

computeLPSArray(pat, M, lps);

int i = 0; // index for txt[]

while (i < N) {

if (pat[j] == txt[i]) {

j++;

i++;

if (j == M) {
printf("Found pattern at index %d \n", i - j);

j = lps[j - 1];

// mismatch after j matches

else if (i < N && pat[j] != txt[i]) {

// Do not match lps[0..lps[j-1]] characters,

// they will match anyway

if (j != 0)

j = lps[j - 1];

else

i = i + 1;

free(lps); // to avoid memory leak

void computeLPSArray(char *pat, int M, int *lps) {

int len = 0; // lenght of the previous longest prefix suffix

int i;

lps[0] = 0; // lps[0] is always 0

i = 1;

// the loop calculates lps[i] for i = 1 to M-1

while (i < M) {

if (pat[i] == pat[len]) {
len++;

lps[i] = len;

i++;

} else // (pat[i] != pat[len])

if (len != 0) {

// This is tricky. Consider the example AAACAAAA and i = 7.

len = lps[len - 1];

// Also, note that we do not increment i here

} else // if (len == 0)

lps[i] = 0;

i++;

// Driver program to test above function

int main() {

char *txt = "ABABDABACDABABCABAB";

char *pat = "ABABCABAB";

KMPSearch(pat, txt);

return 0;

}
Q9 WAP to implement Rabin karp Pattern Matching Algorithm.

#include<stdio.h>

#include<string.h>

// d is the number of characters in input alphabet

#define d 256

/* pat -> pattern

txt -> text

q -> A prime number

*/

void search(char *pat, char *txt, int q)

int M = strlen(pat);

int N = strlen(txt);

int i, j;

int p = 0; // hash value for pattern

int t = 0; // hash value for txt


int h = 1;

// The value of h would be "pow(d, M-1)%q"

for (i = 0; i < M-1; i++)

h = (h*d)%q;

// Calculate the hash value of pattern and first window of text

for (i = 0; i < M; i++)

p = (d*p + pat[i])%q;

t = (d*t + txt[i])%q;

// Slide the pattern over text one by one

for (i = 0; i <= N - M; i++)

// Check the hash values of current window of text and pattern

// If the hash values match then only check for characters on by one

if ( p == t )

/* Check for characters one by one */

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

if (txt[i+j] != pat[j])

break;

}
if (j == M) // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1]

printf("Pattern found at index %d \n", i);

// Calculate hash value for next window of text: Remove leading digit,

// add trailing digit

if ( i < N-M )

t = (d*(t - txt[i]*h) + txt[i+M])%q;

// We might get negative value of t, converting it to positive

if(t < 0)

t = (t + q);

/* Driver program to test above function */

int main()

char *txt = "Sanfoundry C Programming Examples";

char *pat = "San";

int q = 101; // A prime number

search(pat, txt, q);

return 0;

}
Q10 WAP to implement boyce moore Pattern Matching Algorithm.

# include <limits.h>

# include <string.h>

# include <stdio.h>

# define NO_OF_CHARS 256

// A utility function to get maximum of two integers

int max(int a, int b) {

return (a > b) ? a : b;

// The preprocessing function for Boyer Moore's bad character heuristic

void badCharHeuristic(char *str, int size, int badchar[NO_OF_CHARS]) {

int i;

// Initialize all occurrences as -1

for (i = 0; i < NO_OF_CHARS; i++)


badchar[i] = -1;

// Fill the actual value of last occurrence of a character

for (i = 0; i < size; i++)

badchar[(int) str[i]] = i;

void search(char *txt, char *pat) {

int m = strlen(pat);

int n = strlen(txt);

int badchar[NO_OF_CHARS];

badCharHeuristic(pat, m, badchar);

int s = 0; // s is shift of the pattern with respect to text

while (s <= (n - m)) {

int j = m - 1;

while (j >= 0 && pat[j] == txt[s + j])

j--;

if (j < 0) {

printf("\n pattern occurs at shift = %d", s);

s += (s + m < n) ? m - badchar[txt[s + m]] : 1;


}

else

s += max(1, j - badchar[txt[s + j]]);

int main() {

char txt[] = "ABAAABCD";

char pat[] = "ABC";

search(txt, pat);

return 0;

Q11 WAP to implement monte carlo randomized algorithm.

/* Program to compute Pi using Monte Carlo methods */

#include <stdlib.h>

#include <stdio.h>

#include <math.h>

#include <string.h>
#define SEED 35791246

main(int argc, char* argv)

int niter=0;

double x,y;

int i,count=0; /* # of points in the 1st quadrant of unit circle */

double z;

double pi;

printf("Enter the number of iterations used to estimate pi: ");

scanf("%d",&niter);

/* initialize random numbers */

srand(SEED);

count=0;

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

x = (double)rand()/RAND_MAX;

y = (double)rand()/RAND_MAX;

z = x*x+y*y;

if (z<=1) count++;

pi=(double)count/niter*4;

printf("# of trials= %d , estimate of pi is %g \n",niter,pi);


}

You might also like