DAA Correct Version
DAA Correct Version
if arr[mid] == target:
return mid
else:
# Example usage
if __name__ == "__main__":
# Sorted array
target = 10
if result != -1:
else:
def floyd_warshall(graph):
# Number of vertices
V = len(graph)
# Floyd-Warshall algorithm
for k in range(V):
for i in range(V):
for j in range(V):
return dist
# Example usage
if __name__ == "__main__":
INF = float('inf')
graph = [
[INF, 1, 0, INF],
[INF, INF, 2, 0]
result = floyd_warshall(graph)
print(row)
output:
[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
while min_heap:
if current_vertex in visited:
continue
visited.add(current_vertex)
distances[neighbor] = distance
return distances
# Example usage
if __name__ == "__main__":
graph = {
start_node = 'A'
print(f"{vertex}: {distance}")
output:
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:
# Path compression
if self.parent[vertex] != vertex:
self.parent[vertex] = self.find(self.parent[vertex])
return self.parent[vertex]
# Union by rank
root_u = self.find(u)
root_v = self.find(v)
if root_u != root_v:
self.parent[root_v] = root_u
self.parent[root_u] = root_v
else:
self.parent[root_v] = root_u
self.rank[root_u] += 1
def kruskal(graph):
edges = []
edges.append((u, v, weight))
vertices = set(graph.keys())
ds = DisjointSet(vertices)
total_weight = 0
# Step 3: Iterate through the sorted edges and construct the MST
if ds.find(u) != ds.find(v):
mst.append((u, v, weight))
total_weight += weight
ds.union(u, v)
# Example usage
if __name__ == "__main__":
graph = {
}
mst_edges, mst_weight = kruskal(graph)
output:
A -- B (Weight: 1)
B -- C (Weight: 2)
B -- D (Weight: 4)
(a)Quick sort
def quick_sort(arr):
if len(arr) <= 1:
return arr # Base case: A single element or empty array is already sorted
# Example usage
if __name__ == "__main__":
array = [10, 7, 8, 9, 1, 5]
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
result = []
i=j=0
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
# Example usage
if __name__ == "__main__":
array = [10, 7, 8, 9, 1, 5]
output :