Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views23 pages

DAA Programs

The document outlines various programming tasks including implementing algorithms like Merge Sort, Hamiltonian Cycle, Dijkstra's algorithm, and the 0/1 Knapsack problem in different programming languages such as Python, Java, and C. Each section provides code snippets and explanations for the algorithms, showcasing their functionality and applications. Additionally, it covers the implementation of dynamic programming solutions for problems like the Traveling Sales Person and subset sum problems.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views23 pages

DAA Programs

The document outlines various programming tasks including implementing algorithms like Merge Sort, Hamiltonian Cycle, Dijkstra's algorithm, and the 0/1 Knapsack problem in different programming languages such as Python, Java, and C. Each section provides code snippets and explanations for the algorithms, showcasing their functionality and applications. Additionally, it covers the implementation of dynamic programming solutions for problems like the Traveling Sales Person and subset sum problems.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Program 2 - Merge Sort

2. Implement merge sort algorithm to sort a given set of elements and


determine the time required to sort the elements. Repeat the experiment for
different values of n, the number of elements in the list to be sorted and
plot a graph of the time taken versus n. The elements can be read from a
file or can be generated using the random number generator
import matplotlib.pyplot as plt

# Function to merge two subarrays of arr[]


def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r - m

# Create temporary arrays


L = [0] * n1
R = [0] * n2

# Copy data to temp arrays L[] and R[]


for i in range(n1):
L[i] = arr[l + i]
for j in range(n2):
R[j] = arr[m + 1 + j]

# Merge the temp arrays back into arr[l..r]


i = 0 # Initial index of first subarray
j = 0 # Initial index of second subarray
k = l # Initial index of merged subarray

while i < n1 and j < n2:


if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1

# Copy the remaining elements of L[], if any


while i < n1:
arr[k] = L[i]
i += 1
k += 1

# Copy the remaining elements of R[], if any


while j < n2:
arr[k] = R[j]
j += 1
k += 1

# Function to implement MergeSort


def mergeSort(arr, l, r):
if l < r:
m = l + (r - l) // 2 # Midpoint
mergeSort(arr, l, m) # Sort first half
mergeSort(arr, m + 1, r) # Sort second half
merge(arr, l, m, r)
# Driver code
arr = [12, 11, 13, 5, 6, 7]
n = len(arr)

print("Given array is:")


print(arr)

mergeSort(arr, 0, n - 1)

print("\nSorted array is:")


print(arr)

# Plot sorted array


plt.plot(arr, marker='o', linestyle='-', color='b', label='Sorted Array')
plt.xlabel('Index')
plt.ylabel('Value')
plt.title('Merge Sort Output')
plt.legend()
plt.show()

Output:
Program 3
3. Design and implement in Java to find all Hamiltonian Cycles in a
connected undirectd Graph G of n vertices using backtracking principle

import java.util.ArrayList;
import java.util.List;

class HamiltonianCycle {
private int V; // Number of vertices
private int[][] graph;
private List<List<Integer>> allCycles;

public HamiltonianCycle(int[][] graph) {


this.V = graph.length;
this.graph = graph;
this.allCycles = new ArrayList<>();
}

public void findH amiltonianCycles() {


boolean[] visited = new boolean[V];
List<Integer> path = new ArrayList<>();
path.add(0); // Start from vertex 0
visited[0] = true;
backtrack(0, path, visited);
printCycles();
}

private void backtrack(int vertex, List<Integer> path, boolean[] visited) {


if (path.size() == V) {
if (graph[vertex][0] == 1) { // Check if there is an edge back to the starting
vertex
path.add(0);
allCycles.add(new ArrayList<>(path));
path.remove(path.size() - 1);
}
return;
}

for (int nextVertex = 0; nextVertex < V; nextVertex++) {


if (!visited[nextVertex] && graph[vertex][nextVertex] == 1) {
visited[nextVertex] = true;
path.add(nextVertex);
backtrack(nextVertex, path, visited);
path.remove(path.size() - 1);
visited[nextVertex] = false;
}
}
}

private void printCycles() {


if (allCycles.isEmpty()) {
System.out.println("No Hamiltonian Cycle found.");
} else {
System.out.println("Hamiltonian Cycles:");
for (List<Integer> cycle : allCycles) {
System.out.println(cycle);
}
}
}
}

public class Main {


public static void main(String[] args) {
int[][] graph = {
{0, 1, 1, 1, 0, 1},
{1, 0, 1, 1, 1, 0},
{1, 1, 0, 1, 0, 0},
{1, 1, 1, 0, 1, 1},
{0, 1, 0, 1, 1, 0}
};

HamiltonianCycle hc = new HamiltonianCycle(graph);


hc.findHamiltonianCycles();
}
}
Output:
4.Write a C program, from a given vertex in a weighted connected graph,
find shortest i. paths to other vertices using Dijkstra's algorithm.
#include <stdio.h>
#include <limits.h>
#include <stdbool.h>

#define V 5 // Number of vertices in the graph

int minDistance(int dist[], bool sptSet[])


{
int min = INT_MAX, min_index;

for (int v = 0; v < V; v++)


if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;

return min_index;
}

void printSolution(int dist[])


{
printf("Vertex \t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t %d\n", i, dist[i]);
}

void dijkstra(int graph[V][V], int src)


{
int dist[V]; // Output array to store shortest distance
bool sptSet[V]; // Shortest path tree set

for (int i = 0; i < V; i++)


dist[i] = INT_MAX, sptSet[i] = false;

dist[src] = 0;

for (int count = 0; count < V - 1; count++) {


int u = minDistance(dist, sptSet);
sptSet[u] = true;

for (int v = 0; v < V; v++)


if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] +
graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}

printSolution(dist);
}

int main()
{
int graph[V][V] = {
{0, 10, 0, 30, 100},
{10, 0, 50, 0, 0},
{0, 50, 0, 20, 10},
{30, 0, 20, 0, 60},
{100, 0, 10, 60, 0}};

int src = 0;
printf("Dijkstra's Algorithm: Shortest paths from vertex %d\n", src);
dijkstra(graph, src);

return 0;
}

Output:
5. Write a C program to implement the Stack using arrays. Write
Push(),Pop(), and Display() methods to demonstrate its working.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 100 // Maximum size of the stack
int stack[SIZE]; // Array to store stack elements
int top = -1; // Initialize stack as empty
// Function to push an element onto the stack
void Push(int value) {
if (top == SIZE - 1) {
printf("Stack Overflow! Cannot push %d\n", value);
return;
}
stack[++top] = value;
printf("%d pushed to stack\n", value);
}

// Function to pop an element from the stack


void Pop() {
if (top == -1) {
printf("Stack Underflow! Cannot pop from empty stack\n");
return;
}
printf("%d popped from stack\n", stack[top--]);
}

// Function to display all elements of the stack


void Display() {
if (top == -1) {
printf("Stack is empty!\n");
return;
}
printf("Stack elements: ");
for (int i = top; i >= 0; i--) {
printf("%d ", stack[i]);
}
printf("\n");
}

// Main function with menu


int main() {
int choice, value;

while (1) {
printf("\n--- Stack Menu ---\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to push: ");
scanf("%d", &value);
Push(value);
break;
case 2:
Pop();
break;
case 3:
Display();
break;
case 4:
printf("Exiting program.\n");
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}

return 0;
}

Output:
6. Implement a C Program to implement the 0/1 Knapsack problem using
(a) Dynamic Programming method (b) Greedy method.
#include<stdio.h>

int max(int x, int y) { return (x > y)? x : y; }

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 n,we;

printf("Enter the max weight:\n");


scanf("%d",&we);

printf("\nEnter the number of items:\n");

scanf("%d",&n);

int wt[n],val[n];

printf("\nEnter the weight of each item:\n");

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

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

printf("\nEnter the value of each item:\n");

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

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

int val_returned = knapSack(we, wt, val, n);

printf("\nThe maximum value is %d\n",val_returned);

return 0;

Output:
#include <stdio.h>

// A utility function that returns maximum of two integers

int max(int a, int b) {

return (a > b) ? a : b;

// Recursive implementation of 0/1 Knapsack problem

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

// Base Case

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

return 0;

// If weight of the nth item is more than Knapsack capacity W

if (wt[n - 1] > W)

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

// Return the maximum of two cases:

// (1) nth item included

// (2) not included

else

return max(

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

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

);

// Main function

int main() {
int profit[] = {60, 100, 120};

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

int W = 50;

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

printf("Maximum value in Knapsack = %d\n", knapSack(W, weight, profit, n));

return 0;

}
7.Write C programs to (a) Implement All-Pairs Shortest Paths problem using Floyd's
algorithm.

#include <stdio.h>

// Number of vertices in the graph

#define V 4

// Define Infinite as a large enough value. Used for vertices not connected to each other

#define INF 99999

// A utility function to print the solution matrix

void printSolution(int dist[][V]);

// Solves the all-pairs shortest path problem using Floyd Warshall algorithm

void floydWarshall(int dist[][V]) {

int i, j, k;

for (k = 0; k < V; k++) {

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

for (j = 0; j < V; j++) {

if (dist[i][k] + dist[k][j] < dist[i][j])

dist[i][j] = dist[i][k] + dist[k][j];

// Print the shortest distance matrix

printSolution(dist);

/* A utility function to print the distance matrix */

void printSolution(int dist[][V]) {


printf("The following matrix shows the shortest distances between every pair of vertices:\
n");

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

for (int j = 0; j < V; j++) {

if (dist[i][j] == INF)

printf("%7s", "INF");

else

printf("%7d", dist[i][j]);

printf("\n");

int main() {

int graph[V][V] = {

{0, 5, INF, 10},

{INF, 0, 3, INF},

{INF, INF, 0, 1},

{INF, INF, INF, 0}

};

floydWarshall(graph);

return 0;

}
(b)Implement Travelling Sales Person problem using Dynamic programming

#include <stdio.h>
#include <limits.h>
#define MAX 9999
int n = 4;
int distan[20][20] = {
{0, 22, 26, 30},
{30, 0, 45, 35},
{25, 45, 0, 60},
{30, 35, 40, 0}};
int DP[32][8];
int TSP(int mark, int position) {
int completed_visit = (1 << n) - 1;
if (mark == completed_visit) {
return distan[position][0];
}
if (DP[mark][position] != -1) {
return DP[mark][position];
}
int answer = MAX;
for (int city = 0; city < n; city++) {
if ((mark & (1 << city)) == 0) {
int newAnswer = distan[position][city] + TSP(mark | (1 << city), city);
answer = (answer < newAnswer) ? answer : newAnswer;
}
}
return DP[mark][position] = answer;
}
int main() {
for (int i = 0; i < (1 << n); i++) {
for (int j = 0; j < n; j++) {
DP[i][j] = -1;
}
}
printf("Minimum Distance Travelled -> %d\n", TSP(1, 0));
return 0;
}

Output:
8. Design an algorithm and implement a program to find a subset of a given set S = {Sl,
S2,.,Sn} of n positive integers whose SUM is equal to a given positive integer d. For
example, if S ={1, 2, 5, 6, 8} and d= 9, there are two solutions {1,2,6}and {1,8}. Display a
suitable message, if the given problem instance doesn't have a solution.

def subset_sum_recursive(nums, target_sum, index, path, result):

if target_sum == 0:

result.append(path)

return

if index >= len(nums) or target_sum < 0:

return

# Include the current number

subset_sum_recursive(nums, target_sum - nums[index], index + 1, path + [nums[index]],


result)

# Exclude the current number

subset_sum_recursive(nums, target_sum, index + 1, path, result)

def find_subsets_sum_to_d(nums, d):

result = []

subset_sum_recursive(nums, d, 0, [], result)

return result

# Example usage

S = [1, 2, 5, 6, 8]
d=9

subsets = find_subsets_sum_to_d(S, d)

if subsets:

print(f"Subsets that sum up to {d} are:")

for subset in subsets:

print(subset)

else:

print("No subset found that sums up to the target sum.")

You might also like