0% found this document useful (0 votes)
30 views9 pages

DAA Correct Version

The document contains Python implementations of various algorithms including binary search, Floyd-Warshall, Dijkstra's algorithm, Kruskal's algorithm, quick sort, and merge sort. Each algorithm is accompanied by example usage and outputs demonstrating their functionality. The implementations showcase fundamental concepts in computer science such as searching, shortest path finding, and sorting.
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)
30 views9 pages

DAA Correct Version

The document contains Python implementations of various algorithms including binary search, Floyd-Warshall, Dijkstra's algorithm, Kruskal's algorithm, quick sort, and merge sort. Each algorithm is accompanied by example usage and outputs demonstrating their functionality. The implementations showcase fundamental concepts in computer science such as searching, shortest path finding, and sorting.
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/ 9

1.

Python implementation of binary search using the divide-and-conquer approach:


def binary_search(arr, target, low, high):

if low > high:

return -1 # Base case: target not found

mid = (low + high) // 2 # Find the middle index

# Check if the middle element is the target

if arr[mid] == target:

return mid

elif arr[mid] > target:

# Target lies in the left half

return binary_search(arr, target, low, mid - 1)

else:

# Target lies in the right half

return binary_search(arr, target, mid + 1, high)

# Example usage

if __name__ == "__main__":

# Sorted array

array = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

target = 10

# Call binary search

result = binary_search(array, target, 0, len(array) - 1)

if result != -1:

print(f"Element {target} found at index {result}.")

else:

print(f"Element {target} not found in the array.")

output : Element 10 found at index 4.


2. Floyd-Warshall algorithm to find the shortest paths between all pairs of vertices

def floyd_warshall(graph):

# Number of vertices

V = len(graph)

# Initialize the distance matrix

dist = [[graph[i][j] for j in range(V)] for i in range(V)]

# Floyd-Warshall algorithm

for k in range(V):

for i in range(V):

for j in range(V):

# Update the distance if a shorter path is found

dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

return dist

# Example usage

if __name__ == "__main__":

# Adjacency matrix representation of the graph

INF = float('inf')

graph = [

[0, 3, INF, 5],

[2, 0, INF, 4],

[INF, 1, 0, INF],

[INF, INF, 2, 0]

result = floyd_warshall(graph)

print("Shortest distances between every pair of vertices:")

for row in result:

print(row)
output:

Shortest distances between every pair of vertices:

[0, 3, 7, 5]

[2, 0, 6, 4]

[3, 1, 0, 5]

[5, 3, 2, 0]

3. Python implementation of Dijkstra's Algorithm to find the shortest path from a source vertex to
all other vertices in a graph

import heapq

def dijkstra(graph, start):

# Priority queue to select the vertex with the smallest distance

min_heap = [(0, start)] # (distance, vertex)

distances = {vertex: float('inf') for vertex in graph} # Initialize distances to infinity

distances[start] = 0 # Distance to the start vertex is 0

visited = set() # Set to keep track of visited nodes

while min_heap:

current_distance, current_vertex = heapq.heappop(min_heap)

if current_vertex in visited:

continue

visited.add(current_vertex)

# Update the distances for each neighbor

for neighbor, weight in graph[current_vertex]:

distance = current_distance + weight

# If a shorter path is found


if distance < distances[neighbor]:

distances[neighbor] = distance

heapq.heappush(min_heap, (distance, neighbor))

return distances

# Example usage

if __name__ == "__main__":

# Graph represented as an adjacency list

graph = {

'A': [('B', 1), ('C', 4)],

'B': [('A', 1), ('C', 2), ('D', 6)],

'C': [('A', 4), ('B', 2), ('D', 3)],

'D': [('B', 6), ('C', 3)],

start_node = 'A'

shortest_distances = dijkstra(graph, start_node)

print("Shortest distances from node A:")

for vertex, distance in shortest_distances.items():

print(f"{vertex}: {distance}")

output:

Shortest distances from node A:

A: 0

B: 1

C: 3

D: 6
4. Python implementation of Kruskal's Algorithm to find the Minimum Spanning Tree (MST) of a
graph

class DisjointSet:

def __init__(self, vertices):

self.parent = {v: v for v in vertices}

self.rank = {v: 0 for v in vertices}

def find(self, vertex):

# Path compression

if self.parent[vertex] != vertex:

self.parent[vertex] = self.find(self.parent[vertex])

return self.parent[vertex]

def union(self, u, v):

# Union by rank

root_u = self.find(u)

root_v = self.find(v)

if root_u != root_v:

if self.rank[root_u] > self.rank[root_v]:

self.parent[root_v] = root_u

elif self.rank[root_u] < self.rank[root_v]:

self.parent[root_u] = root_v

else:

self.parent[root_v] = root_u

self.rank[root_u] += 1

def kruskal(graph):

# Step 1: Sort all edges in non-decreasing order of their weights

edges = []

for u, neighbors in graph.items():


for v, weight in neighbors:

edges.append((u, v, weight))

edges = sorted(edges, key=lambda x: x[2])

# Step 2: Initialize disjoint sets

vertices = set(graph.keys())

ds = DisjointSet(vertices)

mst = [] # List to store edges in the MST

total_weight = 0

# Step 3: Iterate through the sorted edges and construct the MST

for u, v, weight in edges:

if ds.find(u) != ds.find(v):

mst.append((u, v, weight))

total_weight += weight

ds.union(u, v)

return mst, total_weight

# Example usage

if __name__ == "__main__":

# Graph represented as an adjacency list

graph = {

'A': [('B', 1), ('C', 3)],

'B': [('A', 1), ('C', 2), ('D', 4)],

'C': [('A', 3), ('B', 2), ('D', 5)],

'D': [('B', 4), ('C', 5)],

}
mst_edges, mst_weight = kruskal(graph)

print("Edges in the MST:")

for edge in mst_edges:

print(f"{edge[0]} -- {edge[1]} (Weight: {edge[2]})")

print(f"Total weight of MST: {mst_weight}")

output:

Edges in the MST:

A -- B (Weight: 1)

B -- C (Weight: 2)

B -- D (Weight: 4)

Total weight of MST: 7

5. Python implementations for Quick Sort and Merge Sort

(a)Quick sort

def quick_sort(arr):

if len(arr) <= 1:

return arr # Base case: A single element or empty array is already sorted

pivot = arr[len(arr) // 2] # Choose the middle element as the pivot

left = [x for x in arr if x < pivot]

middle = [x for x in arr if x == pivot]

right = [x for x in arr if x > pivot]

return quick_sort(left) + middle + quick_sort(right)

# Example usage

if __name__ == "__main__":

array = [10, 7, 8, 9, 1, 5]

print("Quick Sort:", quick_sort(array))


output:

Quick Sort: [1, 5, 7, 8, 9, 10]

(b) Merge sort:

def merge_sort(arr):

if len(arr) <= 1:

return arr # Base case: A single element or empty array is already sorted

mid = len(arr) // 2

left = merge_sort(arr[:mid]) # Recursively sort the left half

right = merge_sort(arr[mid:]) # Recursively sort the right half

return merge(left, right)

def merge(left, right):

result = []

i=j=0

# Merge while elements remain in both arrays

while i < len(left) and j < len(right):

if left[i] < right[j]:

result.append(left[i])

i += 1

else:

result.append(right[j])

j += 1

# Append any remaining elements

result.extend(left[i:])

result.extend(right[j:])
return result

# Example usage

if __name__ == "__main__":

array = [10, 7, 8, 9, 1, 5]

print("Merge Sort:", merge_sort(array))

output :

Merge Sort: [1, 5, 7, 8, 9, 10]

You might also like