Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Daa Tanu File

Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

G. L.

Bajaj Institute of Technology and Management


Greater Noida, Uttar Pradesh

Department of Computer Science and Engineering

Session 2023-24 (Even Semester)


Subject / Lab Name: DAA Lab
Subject / Lab Code: KCS-553
Semester: B. Tech. CSE-AIML4 (III)

Lab File

Submitted To: Submitted By:


Ms. Aanchal Vij Nitesh Kumar
(CSE Department) Roll Number:
2101921530100
INDEX

S.NO. Name of Practical Date of Date of Signature Remarks


Practical Submission of Faculty
1. Program for Recursive Binary &
Linear Search.
2. Program for Heap Sort.

3. Program for Merge Sort.

4. Program for Selection Sort.

5. Program for Insertion Sort.

6. Program for Quick Sort.

7. Knapsack Problem using Greedy


Solution.
8. Perform Travelling Salesman
Problem.
9. Find Minimum Spanning Tree using
Kruskal’s Algorithm.
10. Implement N Queen Problem using
Backtracking.
11. Implement, the 0/1 Knapsack
problem using:
(a) Dynamic Programming method
(b) Greedy method.
12. From a given vertex in a weighted
connected graph, find shortest paths
to other vertices using Dijkstra's
algorithm.
13. Find Minimum Cost Spanning
Tree of a given undirected
graph using Prim’s algorithm.
14. Design and implement to find all
Hamiltonian Cycles in a connected
undirected Graph G of n vertices
using backtracking principle.
Experiment no: -1

Aim: Program for Recursive Binary & Linear Search.


Program:
Recursive Binary Search:
#include <stdio.h>
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x) {
return binarySearch(arr, l, mid - 1, x);
}
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int size = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int index = binarySearch(arr, 0, size - 1, x);

if (index == -1) {
printf("Element is not present in array");
}
else {
printf("Element is present at index %d", index);
}

return 0;
}

Recursive Linear Search:


#include <stdio.h>
int linearSearch(int arr[], int size, int key)
{
if (size == 0) {
return -1;
}
if (arr[size - 1] == key) {
return size - 1;
}
return linearSearch(arr, size - 1, key);
}
int main()
{
int arr[] = { 5, 15, 6, 9, 4 };
int key = 4;
int index
= linearSearch(arr, sizeof(arr) / sizeof(int), key);
if (index == -1) {
printf("Key not found in the array.\n");
}
else {
printf("The element %d is found at %d index of the "
"given array \n",
key, index);
}
return 0;
}
Experiment no: -2

Aim: Program for Heap Sort


Program:
#include <stdio.h>

void main()
{
int heap[10], num, i, j, c, rootElement, tempVar;

printf("\n Enter number of elements ");


scanf("%d", &num);
printf(" Enter the num ");
for (i = 0; i < num; i++)
scanf("%d", &heap[i]);
for (i = 1; i < num; i++)
{
c = i;
do
{
rootElement = (c - 1) / 2;
if (heap[rootElement] < heap[c])
{
tempVar = heap[rootElement];
heap[rootElement] = heap[c];
heap[c] = tempVar;
}
c = rootElement;
} while (c != 0);
}

printf("Heap array ");


for (i = 0; i < num; i++)
printf("%d\t ", heap[i]);
for (j = num - 1; j >= 0; j--)
{
tempVar = heap[0];
heap[0] = heap[j];
heap[j] = tempVar;
rootElement = 0;
do
{
c = 2 * rootElement + 1;
if ((heap[c] < heap[c + 1]) && c < j-1)
c++;
if (heap[rootElement]<heap[c] && c<j) {
tempVar = heap[rootElement];
heap[rootElement] = heap[c];
heap[c] = tempVar;
}
rootElement = c;
} while (c < j);
}
printf("The sorted array is ");
for (i = 0; i < num; i++)
printf("\t %d", heap[i]);

}
Experiment no: -3

Aim: Program for Merge Sort


Program:
#include <stdio.h>

void merge(int arr[], int p, int q, int r) {


int n1 = q - p + 1;
int n2 = r - q;
int L[n1], M[n2];
for (int i = 0; i < n1; i++)
L[i] = arr[p + i];
for (int j = 0; j < n2; j++)
M[j] = arr[q + 1 + j];

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

while (i < n1 && j < n2) {


if (L[i] <= M[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = M[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = M[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r) {
if (l < r) { int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

int main() {
int arr[] = {6, 5, 12, 10, 9, 1};
int size = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, size - 1);
printf("Sorted array: \n");
printArray(arr, size);
}
Experiment no: -4

Aim: Program for Selection Sort


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: -5

Aim: Program for Insertion Sort.


Program:
#include <math.h>
#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 n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main()
{
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);

insertionSort(arr, n);
printArray(arr, n);

return 0;
}
Experiment no: -6

Aim: Program for Quick Sort.


Program:
#include <stdio.h>
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
int partition(int array[], int low, int high) {
int pivot = array[high];
int i = (low - 1);
for (int j = low; j < high; j++) {
if (array[j] <= pivot) {
i++;
swap(&array[i], &array[j]);
}
}
swap(&array[i + 1], &array[high]);
return (i + 1);
}
void quickSort(int array[], int low, int high) {
if (low < high) {
int pi = partition(array, low, high);
quickSort(array, low, pi - 1);
quickSort(array, pi + 1, high);
}
}
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}
int main() {
int data[] = {8, 7, 2, 1, 0, 9, 6};

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


printf("Unsorted Array\n");
printArray(data, n);
quickSort(data, 0, n - 1);
printf("Sorted array in ascending order: \n");
printArray(data, n);
}
Experiment no: -7

Aim: Knapsack problem using Greedy Solution.


Program:
#include <stdio.h>
#include <stdlib.h>
struct Item {
int weight;
int value;
};
int compare(const void *a, const void *b) {
double ratioA = (double)(((struct Item *)a)->value) / ((struct Item *)a)->weight;
double ratioB = (double)(((struct Item *)b)->value) / ((struct Item *)b)->weight;
return (ratioB > ratioA) ? 1 : -1;
}
void knapsackGreedy(struct Item items[], int n, int capacity) {
qsort(items, n, sizeof(struct Item), compare);
double totalValue = 0.0;
int currentWeight = 0;
for (int i = 0; i < n; i++) {
if (currentWeight + items[i].weight <= capacity) {
currentWeight += items[i].weight;
totalValue += items[i].value;
} else {
double fraction = (double)(capacity - currentWeight) / items[i].weight;
currentWeight = capacity;
totalValue += fraction * items[i].value;
break;
}
}
printf("Maximum value in Knapsack = %.2lf\n", totalValue);
}

int main() {
int n, capacity;
printf("Enter the number of items: ");
scanf("%d", &n);

struct Item items[n];

printf("Enter the weight and value of each item:\n");


for (int i = 0; i < n; i++) {
printf("Item %d: ", i + 1);
scanf("%d %d", &items[i].weight, &items[i].value);
}

printf("Enter the knapsack capacity: ");


scanf("%d", &capacity);
knapsackGreedy(items, n, capacity);

return 0;
}
Experiment no: -8

Aim: Perform Travelling Salesman Problem.


Program:
#include <stdio.h>

int matrix[25][25], visited_cities[10], limit, cost = 0;

int tsp(int c)
{
int count, nearest_city = 999;
int minimum = 999, temp;
for(count = 0; count < limit; count++)
{
if((matrix[c][count] != 0) && (visited_cities[count] == 0))
{
if(matrix[c][count] < minimum)
{
minimum = matrix[count][0] + matrix[c][count];
}
temp = matrix[c][count];
nearest_city = count;
}
}
if(minimum != 999)
{
cost = cost + temp;
}
return nearest_city;
}
void minimum_cost(int city)
{
int nearest_city;
visited_cities[city] = 1;
printf("%d ", city + 1);
nearest_city = tsp(city);
if(nearest_city == 999)
{
nearest_city = 0;
printf("%d", nearest_city + 1);
cost = cost + matrix[city][nearest_city];
return;
}
minimum_cost(nearest_city);
}

int main()
{
int i, j;
printf("Enter Total Number of Cities:\t");
scanf("%d", &limit);
printf("\nEnter Cost Matrix\n");
for(i = 0; i < limit; i++)
{
printf("\nEnter %d Elements in Row[%d]\n", limit, i + 1);
for(j = 0; j < limit; j++)
{
scanf("%d", &matrix[i][j]);
}
visited_cities[i] = 0;
}
printf("\nEntered Cost Matrix\n");
for(i = 0; i < limit; i++)
{
printf("\n");
for(j = 0; j < limit; j++)
{
printf("%d ", matrix[i][j]);
}
}
printf("\n\nPath:\t");
minimum_cost(0);
printf("\n\nMinimum Cost: \t");
printf("%d\n", cost);
return 0;
}
Experiment no: -9

Aim: Find Minimum Spanning Tree using Kruskal’s Algorithm.


Program:
#include <stdio.h>
#include <stdlib.h>
int comparator(const void* p1, const void* p2)
{
const int(*x)[3] = p1;
const int(*y)[3] = p2;

return (*x)[2] - (*y)[2];


}
void makeSet(int parent[], int rank[], int n)
{
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
int findParent(int parent[], int component)
{
if (parent[component] == component)
return component;

return parent[component]
= findParent(parent, parent[component]);
}
void unionSet(int u, int v, int parent[], int rank[], int n)
{
u = findParent(parent, u);
v = findParent(parent, v);

if (rank[u] < rank[v]) {


parent[u] = v;
}
else if (rank[u] > rank[v]) {
parent[v] = u;
}
else {
parent[v] = u;

// Since the rank increases if


// the ranks of two sets are same
rank[u]++;
}
}
void kruskalAlgo(int n, int edge[n][3])
{
// First we sort the edge array in ascending order
// so that we can access minimum distances/cost
qsort(edge, n, sizeof(edge[0]), comparator);

int parent[n];
int rank[n];

// Function to initialize parent[] and rank[]


makeSet(parent, rank, n);

// To store the minimun cost


int minCost = 0;

printf(
"Following are the edges in the constructed MST\n");
for (int i = 0; i < n; i++) {
int v1 = findParent(parent, edge[i][0]);
int v2 = findParent(parent, edge[i][1]);
int wt = edge[i][2];
if (v1 != v2) {
unionSet(v1, v2, parent, rank, n);
minCost += wt;
printf("%d -- %d == %d\n", edge[i][0],
edge[i][1], wt);
}
}

printf("Minimum Cost Spanning Tree: %d\n", minCost);


}
int main()
{
int edge[5][3] = { { 0, 1, 10 },
{ 0, 2, 6 },
{ 0, 3, 5 },
{ 1, 3, 15 },
{ 2, 3, 4 } };

kruskalAlgo(5, edge);

return 0;
}
Experiment no: -10

Aim: Implement N Queen Problem using Backtracking.


Program:
#define N 4
#include <stdbool.h>
#include <stdio.h>
void printSolution(int board[N][N])
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if(board[i][j])
printf("Q ");
else
printf(". ");
}
printf("\n");
}
}
bool isSafe(int board[N][N], int row, int col)
{
int i, j;
for (i = 0; i < col; i++)
if (board[row][i])
return false;
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return false;
for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j])
return false;

return true;
}
bool solveNQUtil(int board[N][N], int col)
{
if (col >= N)
return true;
for (int i = 0; i < N; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1;
if (solveNQUtil(board, col + 1))
return true;
board[i][col] = 0; // BACKTRACK
}
}
return false;
}
bool solveNQ()
{
int board[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };

if (solveNQUtil(board, 0) == false) {
printf("Solution does not exist");
return false;
}

printSolution(board);
return true;
}
int main()
{
solveNQ();
return 0;
}
Experiment no: -11

Aim: Implement, the 0/1 Knapsack problem using


(a) Dynamic Programming method
(b) Greedy method.

Program:
Dynamic Programming method:
#include<stdio.h>
int max(int a, int b) { return (a > b)? a : b; }
int knapSack(int W, int wt[], int val[], int n)
{
int i, w;
int K[n+1][W+1];
for (i = 0; i <= n; i++)
{
for (w = 0; w <= W; w++)
{
if (i==0 || w==0)
K[i][w] = 0;
else if (wt[i-1] <= w)
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]);
else
K[i][w] = K[i-1][w];
}
}
return K[n][W];
}
int main()
{
int i, n, val[20], wt[20], W;
printf("Enter number of items:");
scanf("%d", &n);

printf("Enter value and weight of items:\n");


for(i = 0;i < n; ++i){
scanf("%d%d", &val[i], &wt[i]);
}

printf("Enter size of knapsack:");


scanf("%d", &W);

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


return 0;
}

Greedy method:
#include <stdio.h>
#include <stdlib.h>
struct Item {
int weight;
int value;
double ratio; // value-to-weight ratio
};
int compare(const void *a, const void *b) {
double ratioA = ((struct Item *)a)->ratio;
double ratioB = ((struct Item *)b)->ratio;
return (ratioB > ratioA) ? 1 : -1;
}
double knapsackGreedy(struct Item items[], int n, int capacity) {
for (int i = 0; i < n; i++) {
items[i].ratio = (double)items[i].value / items[i].weight;
}
qsort(items, n, sizeof(struct Item), compare);

int currentWeight = 0;
double totalValue = 0.0;

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


if (currentWeight + items[i].weight <= capacity) {
// Take the whole item if it fits in the knapsack
currentWeight += items[i].weight;
totalValue += items[i].value;
} else {
double fraction = (double)(capacity - currentWeight) / items[i].weight;
currentWeight = capacity;
totalValue += fraction * items[i].value;
break;
}
}

return totalValue;
}

int main() {
int n, capacity;
printf("Enter the number of items: ");
scanf("%d", &n);

struct Item items[n];

printf("Enter the weight and value of each item:\n");


for (int i = 0; i < n; i++) {
printf("Item %d: ", i + 1);
scanf("%d %d", &items[i].weight, &items[i].value);
}

printf("Enter the knapsack capacity: ");


scanf("%d", &capacity);
double maxValue = knapsackGreedy(items, n, capacity);

printf("Maximum value in Knapsack = %.2lf\n", maxValue);

return 0;
}
Experiment no: -12

Aim: From a given vertex in a weighted connected graph, find shortest paths to
other vertices using Dijkstra’s algorithm.

Program:
#include<stdio.h>
#include<conio.h>
#define infinity 999
void dij(int n,int v,int cost[10][10],int dist[100]){
int i,u,count,w,flag[10],min;
for(i=1;i<=n;i++)
flag[i]=0,dist[i]=cost[v][i];
count=2;
while(count<=n){
min=99;
for(w=1;w<=n;w++)
if(dist[w]<min && !flag[w])
min=dist[w],u=w;
flag[u]=1;
count++;
for(w=1;w<=n;w++)
if((dist[u]+cost[u][w]<dist[w]) && !flag[w])
dist[w]=dist[u]+cost[u][w];
}
}
void main()
{
int n,v,i,j,cost[10][10],dist[10];
clrscr();
printf("\n Enter the number of nodes:");
scanf("%d",&n);
printf("\n Enter the cost matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=infinity;
}
printf("\n Enter the source matrix:");
scanf("%d",&v);
dij(n,v,cost,dist);
printf("\n Shortest path:\n");
for(i=1;i<=n;i++)
if(i!=v)
printf("%d->%d,cost=%d\n",v,i,dist[i]);
getch();
}
Experiment no: -13

Aim: Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s
algorithm.

Program:

#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 printMST(int parent[], int graph[V][V]) {

printf("Edge Weight\n");
for (int i = 1; i < V; i++) {

printf("%d - %d %d \n", parent[i], i, graph[i][parent[i]]);

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; // Start from the first vertex

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

printMST(parent, graph);

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}

};

printf("Minimum Cost Spanning Tree:\n");

primMST(graph);

return 0;

}
Experiment no: -14

Aim: Design and implement to find all Hamiltonian Cycles in a connected


undirected Graph G of n vertices using backtracking principle.

Program:
#include <stdio.h>
#include <stdbool.h>
int graph[MAX_VERTICES][MAX_VERTICES];
int n;
void printSolution(int path[]) {
printf("Hamiltonian Cycle: ");
for (int i = 0; i < n; i++) {
printf("%d ", path[i]);
}
printf("%d\n", path[0]);
}

bool isSafe(int v, int path[], int pos) {


if (graph[path[pos - 1]][v] == 0) {
return false;
}

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


if (path[i] == v) {
return false;
}
}

return true;
}

bool hamiltonianCycleUtil(int path[], int pos) {


if (pos == n) {
if (graph[path[pos - 1]][path[0]] == 1) {
printSolution(path);
return true;
} else {
return false;
}
}

for (int v = 1; v < n; v++) {


if (isSafe(v, path, pos)) {
path[pos] = v;

if (hamiltonianCycleUtil(path, pos + 1)) {


return true;
}
path[pos] = -1;
}
}

return false;
}

void hamiltonianCycle() {
int path[MAX_VERTICES];
for (int i = 0; i < n; i++) {
path[i] = -1;
}
path[0] = 0;

if (!hamiltonianCycleUtil(path, 1)) {
printf("Hamiltonian Cycle does not exist.\n");
}
}

int main() {
printf("Enter the number of vertices in the graph: ");
scanf("%d", &n);

printf("Enter the adjacency matrix of the graph:\n");


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &graph[i][j]);
}
}

hamiltonianCycle();

return 0;
}
OUTPUT
1)

2)

3)

4)

5)
6)

7)

8)
9)

10)
11)

12)
13)

14)

You might also like