DAA Lab File 2[1]
DAA Lab File 2[1]
Semester- V
Lab File
Design and Analysis of Algorithm
(KCS553)
Submitted To : Submitted By :
Faculty Name : Mr. Pankaj Singh Yadav Name :
Designation : Assistant Professor Roll No. :
Section :
Table of Contents
• Vision and Mission Statements of the Institute
• List of Experiments
• Index
i. To provide broad based quality education with knowledge and attitude to succeed in Computer Science &
Engineering careers.
ii. To prepare students for emerging trends in computer and related industry.
iii. To develop competence in students by providing them skills and aptitude to foster culture of continuous and
lifelong learning.
iv. To develop practicing engineers who investigate research, design, and find workable solutions to complex
engineering problems with awareness & concern for society as well as environment.
ii. Graduates will possess capability of designing successful innovative solutions to real life problems that are
technically sound, economically viable and socially acceptable.
iii. Graduates will be competent team leaders, effective communicators and capable of working in
multidisciplinary teams following ethical values.
iv. The graduates will be capable of adapting to new technologies/tools and constantly upgrading their knowledge
and skills with an attitude for lifelong learning
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
Computer Science & Engineering sciences.
3. Design/development of solutions: Design solutions for complex Computer Science & Engineering
problems and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental considerations.
4. Investigation: Use research-based knowledge and research methods including design of experiments,
analysis and interpretation of data, and synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering
and IT tools including prediction and modelling to complex Computer Science & Engineering activities with
an understanding of the limitations.
6. The Engineering and Society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice in the field of Computer Science and Engineering.
7. Environment and sustainability: Understand the impact of the professional Computer Science &
Engineering solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
Computer Science & Engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex Computer Science & Engineering activities with
the engineering community and with society at large, such as, being able to comprehend and write effective
reports and design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the Computer Science
& Engineering and management principles and apply these to one’s own work, as a member and leader in a
team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in independent
and life-long learning in the broadest context of technological change.
1. Use algorithms, data structures/management, software design, concepts of programming languages and
computer organization and architecture.
2. Understand the processes that support the delivery and management of information systems within a
specific application environment.
Course Outcomes
Level to be
*Level of Bloom’s Taxonomy Level to be met *Level of Bloom’s Taxonomy
Met
L1: Remember 1 L2: Understand 2
L3: Apply 3 L4: Analyze 4
L5: Evaluate 5 L6: Create 6
List of Experiments
INDEX
S Lab Experiment Date of Date of Marks Faculty
No Experiment Submission Signature
a) Implementation of analysis of
1 Linear search using recursive
function 05/10/23 19/10/23
b) Implementation of analysis of
Binary search using recursive
function
a) Implementation and analysis of
2 Insertion sort
b) Implementation and analysis of 05/10/23 19/10/23
Bubble sort
c) Implementation and analysis of
Selection sort
a) Implementation and analysis of
3 Merge sort
b) Implementation and analysis of 19/10/23 26/10/23
Quick sort
a) Implementation and analysis of
4 Heap sort
b) Implementation and analysis of 19/10/23 26/10/23
Counting sort
a) Implementation and analysis of
5 Radix sort
b) Implementation and analysis of 26/10/23 31/10/23
Shell sort
a) Implementation and anaylsis of
6 Activity Selection Problem
b) Implementation and anaylsis of 26/10/23 31/10/23
knapsack problem using greedy
solution
a) Implementation and Analysis of 0/1
7 Knapsack problem using dynamic
programming method 31/10/23 06/11/23
b) Implementation and Analysis LCS
a) Implementation of Kruskal’s
8 algorithm to find MST
b) Implementation of Prim’s algorithm 06/11/23 19/11/23
to find MST
a) Implementation of Warshall’s
9 algorithm for all pair shortest path
b) Implementation of Dijkstra’s 19/11/23 26/11/23
algorithm for single source shortest
path
a) Implementation of N- Queen
10
problem using backtracking
b) Implementation of sum of subset 26/11/23 30/11/23
problem using backtracking
a) Implementation of Naïve String
11
Matching Algorithm
b) Implementation of Rabin Karp 30/11/23 05/12/23
Matching Algorithm
Pseudocode:-
Function:
Algorithm:-
Program:-
#include <stdio.h>
int RecursiveLS(int arr[], int value, int index, int n)
{
int pos = 0;
if(index >= n)
{
return 0;
}
else
{
return RecursiveLS(arr, value, index+1, n);
}
return pos;
}
int main()
{
int n, value, pos, m = 0, arr[100];
printf("Enter the total elements in the array ");
scanf("%d", &n);
Pseudocode:-
Function:
Algorithm:-
Program:-
#include <stdio.h>
int recursiveBinarySearch(int array[], int start_index, int end_index, int element)
{
if (end_index >= start_index)
{
int middle = start_index + (end_index - start_index )/2;
if (array[middle] == element)
return middle;
if (array[middle] > element)
return recursiveBinarySearch(array, start_index, middle-1, element);
return recursiveBinarySearch(array, middle+1, end_index, element);
}
return -1;
}
int main(void)
{
int array[] = {1, 4, 7, 9, 16, 56, 70};
int n = 7;
int element = 9;
int found_index = recursiveBinarySearch(array, 0, n-1, element);
if(found_index == -1 )
{
printf("Element not found in the array ");
}
else
{
printf("Element found at index : %d",found_index);
}
return 0;
}
Function:
InsertionSort(array)
n = length of array
for i = 1 to n - 1
key = array[i]
j=i-1
// Move elements greater than key to one position ahead of their current position
while j >= 0 and array[j] > key
array[j + 1] = array[j]
j=j-1
array[j + 1] = key
Algorithm:-
• Start with the second element (or index 1) and consider it as the "key".
• Compare the key element with the elements before it in the sorted subarray.
• If the key element is smaller, shift the greater elements one position ahead to make space for the key
element.
• Repeat steps 2 and 3 until the key element is in its correct position within the sorted subarray.
• Move to the next element and repeat the process until the entire array is sorted.
Program:-
#include <stdio.h>
void printArray(int array[], int size)
{
for (int i = 0; i < size; i++)
{
printf("%d ", array[i]);
}
printf("\n");
}
Pseudocode:-
procedure bubbleSort(A: list of sortable items)
n := length(A)
repeat
swapped := false
for i := 1 to n-1 inclusive do
if A[i-1] > A[i] then
swap A[i-1] and A[i]
swapped := true
end if
end for
until not swapped
end procedure
Algorithm:-
procedure bubbleSort(A: array of elements)
n := length(A)
swapped := true
while swapped
swapped := false
for i := 1 to n-1
if A[i-1] > A[i] then
swap A[i-1] and A[i]
swapped := true
end if
end for
end while
end procedure
Program:-
#include <stdio.h>
void bubbleSort(int array[], int size)
{
for (int step = 0; step < size - 1; ++step)
{
for (int i = 0; i < size - step - 1; ++i)
{
if (array[i] > array[i + 1])
{
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
}
void printArray(int array[], int size)
{
for (int i = 0; i < size; ++i)
{
printf("%d ", array[i]);
}
printf("\n");
}
int main()
{
int data[] = {-2, 45, 0, 11, -9};
int size = sizeof(data) / sizeof(data[0]);
bubbleSort(data, size);
printf("Sorted Array in Ascending Order:\n");
printArray(data, size);
}
Pseudocode:-
procedure selectionSort(A: array of elements)
n := length(A)
for i := 0 to n-1
// Assume the current index is the minimum
minIndex := i
// Find the index of the minimum element in the unsorted part of the array
for j := i+1 to n-1
if A[j] < A[minIndex] then
minIndex := j
end if
end for
Algorithm:-
procedure insertionSort(A: array of elements)
n := length(A)
for i := 1 to n-1
key := A[i]
j := i - 1
// Move elements that are greater than key to one position ahead
while j >= 0 and A[j] > key
A[j + 1] := A[j]
j := j - 1
// Insert key into the correct position in the sorted part of the array
Program:-
#include <stdio.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void selectionSort(int array[], int size)
{
for (int step = 0; step < size - 1; step++)
{
int min_idx = step;
for (int i = step + 1; i < size; i++)
{
if (array[i] < array[min_idx])
min_idx = i;
}
swap(&array[min_idx], &array[step]);
}
}
void printArray(int array[], int size)
{
for (int i = 0; i < size; ++i)
{
printf("%d ", array[i]);
}
printf("\n");
}
int main()
{
int data[] = {20, 12, 10, 15, 2};
int size = sizeof(data) / sizeof(data[0]);
selectionSort(data, size);
printf("Sorted array in Acsending Order:\n");
printArray(data, size);
}
Experiment No. :- 3
Pseudocode:-
MergeSort(arr):
if length of arr <= 1:
return arr
// Split the array into two halves
mid = length of arr / 2
left = arr[0 to mid-1]
right = arr[mid to end]
return merged
Merge(left, right):
result = []
leftIndex = 0
rightIndex = 0
Algorithm:-
Program:-
// C program for Merge Sort
#include <stdio.h>
#include <stdlib.h>
merge(arr, l, m, r);
}
}
// UTILITY FUNCTIONS
// Function to print an array
void printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
// Driver code
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
Pseudocode:-
Algorithm:-
Swap(arr, i, j):
// Helper function to
Program:-
#include <stdio.h>
int i, j, k;
i = 0;
j = 0;
k = start;
int main() {
int arr[] = {6, 5, 12, 10, 9, 1};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Original array\n");
display(arr, size);
printf("Sorted array\n");
display(arr, size);
}
Experiment No. :- 4
Pseudocode:-
procedure heapSort(arr):
n := length(arr)
// If the largest is not the root, swap them and recursively heapify the affected sub-tree
if largest != i:
swap(arr[i], arr[largest])
heapify(arr, n, largest)
Algorithm:-
procedure heapSort(arr):
n := length(arr)
// Sorting phase
for i from n - 1 down to 1:
// Swap the root (maximum element) with the last element
swap(arr[0], arr[i])
// If the largest is not the root, swap and recursively heapify the affected sub-tree
if largest != i:
swap(arr[i], arr[largest])
heapify(arr, n, largest)
Program:-
// Heap Sort in C
#include <stdio.h>
// left = 2*i + 1
int left = 2 * i + 1;
// right = 2*i + 2
int right = 2 * i + 2;
largest = left;
largest = right;
swap(&arr[i], &arr[largest]);
// Heap sort
for (int i = N - 1; i >= 0; i--) {
swap(&arr[0], &arr[i]);
// Driver's code
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
heapSort(arr, N);
printf("Sorted array is\n");
printArray(arr, N);
}
Pseudocode:-
procedure countingSort(arr):
// Find the maximum value in the input array
maxVal := findMax(arr)
// Update the count array to store the actual position of each element in the sorted array
for i from 1 to maxVal:
count[i] := count[i] + count[i - 1]
Algorithm:-
countingSort(arr, n)
maximum <- find the largest element in arr
create a count array of size maximum+1
initialise count array with all 0's
for i <- 0 to n
find the total frequency/ occurrences of each element and
store the count at ith index in count arr
Program:-
#include <stdio.h>
int x = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > x)
x = arr[i];
}
int count_arr[10];
Pseudocode:-
Radix-Sort(A, d)
for j = 1 to d do
int count[10] = {0};
for i = 0 to n do
count[key of(A[i]) in pass j]++
for k = 1 to 10 do
count[k] = count[k] + count[k-1]
for i = n-1 downto 0 do
result[ count[key of(A[i])] ] = A[j]
count[key of(A[i])]--
for i=0 to n do
A[i] = result[i]
end for(j)
end func
Algorithm:-
radixSort(arr)
max = largest element in the given array
d = number of digits in the largest element (or, max)
Now, create d buckets of size 0 - 9
for i -> 0 to d
sort the array elements using counting sort (or any stable sort) according to the digits at
the ith place
Program:-
#include<stdio.h>
#include<stdlib.h>
int *Radix_sort(int *arr, int size);
int *Count_sort(int *arr, int size, int Exponent);
int maximum(int *arr,int length);
int minimum(int *arr,int length);
int main()
{
int i, size;
int *arr;
printf("Enter the array size: ");
scanf("%d",&size);
arr = (int *) malloc( sizeof( int ) * size );
if(arr==NULL)
{
exit(-1);//abnormal termination.
}
else
{
// Entering the array values
printf("Enter the array\n");
for(i = 0; i < size; i++)
{
printf("arr[ %d ] = ",i);
scanf("%d",&arr[i]);
}
printf("Array before sorting:\n");
for(i = 0; i < size; i++)
{
printf("arr[%d] = %d\n",i,arr[i]);
}
arr = Radix_sort(arr,size);
}
printf("ARRAY AFTER SORTING: \n");
for(int i=0;i<size;i++)
{
printf("arr[ %d ] = %d \n",i ,arr[i]);
}
}
for(int i=0;i<size;i++)
{
frequency_array[ (arr[i]/Exponent)%10 ]++;
}
Pseudocode:-
procedure shellSort(arr):
n := length(arr)
// Shift earlier gap-sorted elements until the correct position for arr[i] is found
j := i
while j >= gap and arr[j - gap] > temp:
arr[j] := arr[j - gap]
j := j - gap
// Shift earlier gap-sorted elements until the correct position for arr[i] is found
j := i
while j >= gap and arr[j - gap] > temp:
arr[j] := arr[j - gap]
j := j - gap
#include <stdio.h>
// Shell sort
void shellSort(int array[], int n) {
// Rearrange elements at each n/2, n/4, n/8, ... intervals
for (int interval = n / 2; interval > 0; interval /= 2) {
for (int i = interval; i < n; i += 1) {
int temp = array[i];
int j;
for (j = i; j >= interval && array[j - interval] > temp; j -= interval) {
array[j] = array[j - interval];
}
array[j] = temp;
}
}
}
// Print an array
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}
// Driver code
int main() {
int data[] = {9, 8, 3, 7, 5, 6, 4, 1};
int size = sizeof(data) / sizeof(data[0]);
shellSort(data, size);
printf("Sorted array: \n");
printArray(data, size);
}
Experiment No. :- 6
Pseudocode:-
procedure activitySelection(start, finish):
// Assuming activities are already sorted by their finish times
n := length(start)
// The first activity is always selected
selectedActivities := [0]
return selectedActivities
Algorithm:-
procedure activitySelection(start, finish):
// Assuming activities are already sorted by their finish times
n := length(start)
return selectedActivities
Program:-
#include <stdio.h>
printf("Selected activities:\n");
int main() {
// Example activities array
struct Activity activities[] = {
{1, 2}, {3, 4}, {0, 6}, {5, 7}, {8, 9}, {5, 9}
};
return 0;
}
Pseudocode:-
procedure fractionalKnapsack(values, weights, capacity):
n := length(values)
// Initialize variables
totalValue := 0.0
remainingCapacity := capacity
return totalValue
Algorithm:-
procedure fractionalKnapsack(values, weights, capacity):
n := length(values)
// Initialize variables
totalValue := 0.0
remainingCapacity := capacity
// Update variables
totalValue := totalValue + amountTaken * ratios[i]
remainingCapacity := remainingCapacity - amountTaken
return totalValue
Program:-
#include <stdio.h>
#include <stdlib.h>
return totalValue;
}
int main() {
// Example items array
struct Item items[] = {
{60, 10}, {100, 20}, {120, 30}
};
int n = sizeof(items) / sizeof(items[0]);
int capacity = 50;
return 0;
}
Experiment No. :-7
Objective 1:- Implementation and analysis of the 0/1 Knapsack problem using dynamic programming
method
Pseudocode:-
function knapsack(weights[1..n], values[1..n], capacity)
// Create a table to store the maximum values for subproblems
let dp[0..n][0..capacity] be a 2D array
Dynamic-0-1-knapsack (v, w, n, W)
for w = 0 to W do
c[0, w] = 0
for i = 1 to n do
c[i, 0] = 0
for w = 1 to W do
if wi ≤ w then
c[i, w] = c[i-1, w]
Program:-
// Driver code
int main()
{
int profit[] = { 60, 100, 120 };
int weight[] = { 10, 20, 30 };
int W = 50;
int n = sizeof(profit) / sizeof(profit[0]);
printf("%d", knapSack(W, weight, profit, n));
return 0;
}
Algorithm:-
Initialize: Create a 2D array dp of size (m+1) x (n+1) to store the lengths of LCS.
Dynamic Programming: Iterate over each character in X and Y using two nested loops.
Backtracking (Optional): Starting from the bottom-right corner of the dp array, backtrack to reconstruct the
LCS.
If X[i] == Y[j], include X[i] (or Y[j]) in the LCS, move diagonally up and left in the dp array.
If X[i] != Y[j], move in the direction of the larger value (either up or left).
Output: The length of the LCS is dp[m][n].
Optionally, the LCS itself can be reconstructed using the backtracking information.
Program:-
// The longest common subsequence in C
#include <stdio.h>
#include <string.h>
int i, j, m, n, LCS_table[20][20];
char S1[20] = "ACADB", S2[20] = "CBDA", b[20][20];
void lcsAlgo() {
m = strlen(S1);
n = strlen(S2);
int main() {
lcsAlgo();
printf("\n");
}
Experiment No. :-8
3. Procedure Kruskal(G):
6. Create an empty priority queue or list to store the edges sorted by weight.
7. Create an array parent[V] to keep track of the parent of each vertex (initially each vertex is its own parent).
11. if FindSet(u) is not equal to FindSet(v): // Check if adding the edge forms a cycle.
Program:-
// Kruskal's algorithm in C
#include <stdio.h>
#define MAX 30
int u, v, w;
} edge;
edge data[MAX];
int n;
} edge_list;
edge_list elist;
int Graph[MAX][MAX], n;
edge_list spanlist;
void kruskalAlgo();
void sort();
void print();
void kruskalAlgo() {
elist.n = 0;
if (Graph[i][j] != 0) {
elist.data[elist.n].u = i;
elist.data[elist.n].v = j;
elist.data[elist.n].w = Graph[i][j];
elist.n++;
sort();
belongs[i] = i;
spanlist.n = 0;
if (cno1 != cno2) {
spanlist.data[spanlist.n] = elist.data[i];
spanlist.n = spanlist.n + 1;
return (belongs[vertexno]);
int i;
if (belongs[i] == c2)
belongs[i] = c1;
}
// Sorting algo
void sort() {
int i, j;
edge temp;
temp = elist.data[j];
elist.data[j + 1] = temp;
void print() {
int i, cost = 0;
}
printf("\nSpanning tree cost: %d", cost);
int main() {
int i, j, total_cost;
n = 6;
Graph[0][0] = 0;
Graph[0][1] = 4;
Graph[0][2] = 4;
Graph[0][3] = 0;
Graph[0][4] = 0;
Graph[0][5] = 0;
Graph[0][6] = 0;
Graph[1][0] = 4;
Graph[1][1] = 0;
Graph[1][2] = 2;
Graph[1][3] = 0;
Graph[1][4] = 0;
Graph[1][5] = 0;
Graph[1][6] = 0;
Graph[2][0] = 4;
Graph[2][1] = 2;
Graph[2][2] = 0;
Graph[2][3] = 3;
Graph[2][4] = 4;
Graph[2][5] = 0;
Graph[2][6] = 0;
Graph[3][0] = 0;
Graph[3][1] = 0;
Graph[3][2] = 3;
Graph[3][3] = 0;
Graph[3][4] = 3;
Graph[3][5] = 0;
Graph[3][6] = 0;
Graph[4][0] = 0;
Graph[4][1] = 0;
Graph[4][2] = 4;
Graph[4][3] = 3;
Graph[4][4] = 0;
Graph[4][5] = 0;
Graph[4][6] = 0;
Graph[5][0] = 0;
Graph[5][1] = 0;
Graph[5][2] = 2;
Graph[5][3] = 0;
Graph[5][4] = 3;
Graph[5][5] = 0;
Graph[5][6] = 0;
kruskalAlgo();
print();
Return MSTSet
Algorithm:-
Create a set MSTSet to keep track of vertices included in the Minimum Spanning Tree (MST).
Initialize key[] array with a large value for all vertices and set key[start] to 0, where start is the starting vertex.
Repeat the following steps until all vertices are included in the MST:
a. Pick the minimum key vertex u from the set of vertices not yet included in MST.
b. Include u in MSTSet.
c. Update the key values of all adjacent vertices of u if they are smaller than the current key values.
#include <stdio.h>
#include <limits.h>
return min_index;
}
return 0;
}
Experiment No. :- 9
Objective 1:- Implementation of Warshal’s Algorithm for all pair shortest path.
Pseudocode:-
procedure Warshall(graph):
V <- number of vertices in graph
dist[][] <- copy of graph[][]
#include <stdio.h>
#define V 4
int i, j, k;
intermediate vertices.
becomes {0, 1, 2, .. k} */
// dist[i][j]
}
}
printSolution(dist);
printf(
if (dist[i][j] == INF)
printf("%7s", "INF");
else
printf("%7d", dist[i][j]);
printf("\n");
// driver's code
int main()
(0)------->(3)
| /|\
5| |
| |1
\|/ |
(1)------->(2)
3 */
{ INF, 0, 3, INF },
{ INF, INF, 0, 1 },
// Function call
floydWarshall(graph);
return 0;
Objective 2:- Implementation of Dijkstra’s Algorithm for single source shortest path.
Pseudocode:-
function Dijkstra(graph, source):
mark u as processed
update distance to v
Algorithm:-
Create a set to store vertices, distances, and a boolean array to track if a vertex is included in the shortest path
tree.
Initialize all distances as INFINITE and set the source vertex distance to 0.
Repeat the following until all vertices are included in the shortest path tree:
a. Pick the minimum distance vertex from the set of vertices not yet processed.
b. Update the distance values of the adjacent vertices of the picked vertex.
c. Mark the picked vertex as processed.
The array containing the shortest distances from the source vertex represents the shortest path from the source
to all other vertices.
Program:-
#include <stdio.h>
#include <limits.h>
return min_index;
}
dist[src] = 0;
printSolution(dist);
}
int main() {
int graph[V][V] = {
{0, 1, 4, 0, 0, 0},
{1, 0, 4, 2, 7, 0},
{4, 4, 0, 3, 5, 0},
{0, 2, 3, 0, 4, 6},
{0, 7, 5, 4, 0, 7},
{0, 0, 0, 6, 7, 0}
};
dijkstra(graph, 0);
return 0;
}
Experiment No. :-10
if col >= N:
Algorithm:-
Start in the leftmost column.
If all queens are placed, return true.
Try all rows in the current column. For each row, do the following:
a. If the queen can be placed safely in this row and column, mark this cell and recursively try to place the queen
in the next column.
b. If placing the queen in the current cell leads to a solution, return true.
c. If placing the queen in the current cell does not lead to a solution, unmark this cell (backtrack) and try the
next row.
If all rows have been tried and none worked, return false to trigger backtracking.
Program:-
#include <stdio.h>
#include <stdbool.h>
return true;
}
board[i][col] = 0; // Backtrack
}
}
return false;
}
bool solveNQueens() {
int board[N][N] = {0};
if (!solveNQueensUtil(board, 0)) {
printf("Solution does not exist");
return false;
}
printSolution(board);
return true;
}
int main() {
solveNQueens();
return 0;
}
function subsetSum(s, k, r)
subset[k] = 1
if s+k is equal to sum
displaySubset()
else if s+k+subset[k+1] is less than or equal to sum
subsetSum(s+k, k+1, r-k)
if s+r-k is greater than or equal to sum and s+subset[k+1] is less than or equal to sum
subset[k] = 0
subsetSum(s, k+1, r-k)
function solveSubsetSum()
total = 0
for i from 1 to n
total += i
Print "Solutions:"
subsetSum(0, 1, total)
function main()
Input n
Input sum
solveSubsetSum()
return 0
Algorithm:-
Input the number of elements n and the desired sum sum from the user.
Calculate the total sum of all elements from 1 to n.
Check if there is any possibility of obtaining the desired sum. If not, print "No solution" and exit.
Initialize the subset array and call the subsetSum function with appropriate parameters.
The subsetSum function uses backtracking to explore all possible subsets that sum to the desired sum.
If a subset is found, display it.
Continue exploring subsets until all possibilities are exhausted.
Program:-
#include <stdio.h>
int subset[MAX];
int n, sum;
void displaySubset() {
printf("Subset: { ");
for (int i = 0; i < n; i++) {
if (subset[i] == 1) {
printf("%d ", i + 1);
}
}
printf("}\n");
}
void solveSubsetSum() {
int total = 0;
for (int i = 1; i <= n; i++) {
total += i;
}
printf("Solutions:\n");
subsetSum(0, 1, total);
}
int main() {
printf("Enter the number of elements: ");
scanf("%d", &n);
solveSubsetSum();
return 0;
}
Experiment No. :-11
for i = 0 to n - m
j=0
while j < m and text[i + j] = pattern[j]
j=j+1
end while
if j = m
print "Pattern found at index", i
end if
end for
end procedure
Algorithm:-
Initialize variables n and m as the lengths of the text and pattern, respectively.
Iterate from i = 0 to n - m:
Initialize a variable j to 0.
Increment j.
If j becomes equal to m, print the index i as the pattern is found starting at that index.
Program:-
#include <stdio.h>
#include <string.h>
int M = strlen(pat);
int N = strlen(txt);
int j;
if (txt[i + j] != pat[j])
break;
if (j
// Driver's code
int main()
{
// Function call
search(pat, txt);
return 0;
// Calculate d^(m-1) % q
h = d^(m-1) % q
// Calculate hash values for the pattern and the initial substring in the text
patternHash = calculateHash(pattern, m, d, q)
textHash = calculateHash(text[0:m], m, d, q)
// Iterate through the text
for i from 0 to n-m:
// Check if the hash values match
if patternHash = textHash:
// Check character by character if it's a match
if text[i:i+m] equals pattern:
print "Pattern found at index", i
Algorithm:-
Preprocess the pattern to calculate its hash value.
Slide the pattern over the text one character at a time and recalculate the hash value of the current substring.
If the hash values match, compare each character of the pattern with the corresponding characters in the
substring to confirm the match.
Program:-
#include <stdio.h>
#include <string.h>
#define d 256
*/
int M = strlen(pat);
int N = strlen(txt);
int i, j;
int p = 0; // hash value for pattern
int h = 1;
h = (h * d) % q;
// window of text
p = (d * p + pat[i]) % q;
t = (d * t + txt[i]) % q;
if (p == t) {
if (txt[i + j] != pat[j])
break;
if (j == M)
if (i < N - M) {
// it to positive
if (t < 0)
t = (t + q);
/* Driver Code */
int main()
// A prime number
int q = 101;
// function call
search(pat, txt, q);
return 0;
}
Experiment No. :-12
Pseudocode:-
function hamiltonianCycle(graph):
path[i] = -1
path[0] = 0
else:
printSolution(path)
if pos is equal to V:
return true
else:
return false
path[pos] = v
if hamiltonianCycleUtil(graph, path, pos + 1) is true:
return true
path[pos] = -1 // Backtrack
return false
if graph[path[pos - 1]][v] is 0:
return false
if path[i] is equal to v:
return false
return true
function printSolution(path):
print path[i]
Algorithm:-
Initialize the path array to store the Hamiltonian cycle.
Start from the first vertex and set it as the starting point in the path array.
Use backtracking to try all possible vertices for the next position in the path array.
Check if the chosen vertex is adjacent to the last added vertex and has not been included before.
If a Hamiltonian cycle is found, print the solution.
Program:-
#include <stdio.h>
#include <stdbool.h>
printSolution(path);
}
return true;
}
int main() {
bool graph[V][V] = {
{0, 1, 1, 1, 0},
{1, 0, 1, 0, 1},
{1, 1, 0, 1, 1},
{1, 0, 1, 0, 0},
{0, 1, 1, 0, 0}
};
hamiltonianCycle(graph);
return 0;
}
Experiment No. :-13
Objective:- Implementation of Insertion operation in RB Tree
Pseudocode:-
RB-INSERT(T, z):
y = NIL
x = T.root
while x != NIL:
y=x
x = x.left
else:
x = x.right
z.parent = y
if y == NIL:
T.root = z
y.left = z
else:
y.right = z
z.color = RED
// Fix violations
RB-INSERT-FIXUP(T, z)
RB-INSERT-FIXUP(T, z):
while z.parent.color == RED:
if z.parent == z.parent.parent.left:
y = z.parent.parent.right
if y.color == RED:
// Case 1: Recolor
z.parent.color = BLACK
y.color = BLACK
z.parent.parent.color = RED
z = z.parent.parent
else:
if z == z.parent.right:
z = z.parent
LEFT-ROTATE(T, z)
z.parent.color = BLACK
z.parent.parent.color = RED
RIGHT-ROTATE(T, z.parent.parent)
else:
// Symmetric case
//
T.root.color = BLACK
Algorithm:-
Insertion:Perform a standard binary search tree insertion.
Fix Violations: If the parent of the newly inserted node is BLACK, the tree remains valid, and no further action
is needed.
If the parent is RED, there may be a violation of the Red-Black Tree properties.
Recolor or Restructure: Check the color of the uncle (sibling of the parent of the new node).
If the uncle is RED, recolor the parent and uncle to BLACK and the grandparent to RED. Then, continue the
fix-up process on the grandparent.
If the uncle is BLACK or NULL: If the new node and its parent are in a zig-zag configuration, perform a
rotation (left-right or right-left) to make them in a line.
After rotation, recolor the original parent to BLACK, the original grandparent to RED, and perform another
rotation.
If the new node and its parent are in a line configuration, perform a rotation to balance the tree.
Recolor the original parent to BLACK and the original grandparent to RED.
Root Adjustment: After the fix-up process, the root of the tree may change. Ensure that the root is always
BLACK
Program:-
#include <stdio.h>
#include <stdlib.h>
struct node {
int d;
int c;
struct node* p;
struct node* r;
struct node* l;
};
struct node* root = NULL;
struct node* bst(struct node* trav,
struct node* temp)
{
if (trav == NULL)
return temp;
if (temp->d < trav->d)
{
trav->l = bst(trav->l, temp);
trav->l->p = trav;
}
else if (temp->d > trav->d)
{
trav->r = bst(trav->r, temp);
trav->r->p = trav;
}
return trav;
}
void rightrotate(struct node* temp)
{
struct node* left = temp->l;
temp->l = left->r;
if (temp->l)
temp->l->p = temp;
left->p = temp->p;
if (!temp->p)
root = left;
else if (temp == temp->p->l)
temp->p->l = left;
else
temp->p->r = left;
left->r = temp;
temp->p = left;
}
else {
if (pt == parent_pt->r) {
leftrotate(parent_pt);
pt = parent_pt;
parent_pt = pt->p;
}
rightrotate(grand_parent_pt);
int t = parent_pt->c;
parent_pt->c = grand_parent_pt->c;
grand_parent_pt->c = t;
pt = parent_pt;
}
}
else {
struct node* uncle_pt = grand_parent_pt->l;
if ((uncle_pt != NULL) && (uncle_pt->c == 1))
{
grand_parent_pt->c = 1;
parent_pt->c = 0;
uncle_pt->c = 0;
pt = grand_parent_pt;
}
else {
if (pt == parent_pt->l) {
rightrotate(parent_pt);
pt = parent_pt;
parent_pt = pt->p;
}
/* Case : 3
pt is right child of its parent
Left-rotation required */
leftrotate(grand_parent_pt);
int t = parent_pt->c;
parent_pt->c = grand_parent_pt->c;
grand_parent_pt->c = t;
pt = parent_pt;
}
}
}
}
void inorder(struct node* trav)
{
if (trav == NULL)
return;
inorder(trav->l);
printf("%d ", trav->d);
inorder(trav->r);
}
int main()
{
int n = 7;
int a[7] = { 7, 6, 5, 4, 3, 2, 1 };
for (int i = 0; i < n; i++) {
struct node* temp
= (struct node*)malloc(sizeof(struct node));
temp->r = NULL;
temp->l = NULL;
temp->p = NULL;
temp->d = a[i];
temp->c = 1;
root = bst(root, temp);
fixup(root, temp);
root->c = 0;
}
printf("Inorder Traversal of Created Tree\n");
inorder(root);
return 0;
}
Experiment No. :-14
return;
}
void traversal(struct BTreeNode *myNode) {
int i;
if (myNode) {
for (i = 0; i < myNode->count; i++) {
traversal(myNode->link[i]);
printf("%d ", myNode->val[i + 1]);
}
traversal(myNode->link[i]);
}
}
int main() {
int val, ch;
insert(8);
insert(9);
insert(10);
insert(11);
insert(15);
insert(16);
insert(17);
insert(18);
insert(20);
insert(23);
traversal(root);
printf("\n");
search(11, &ch, root);
}