Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit d65aecf

Browse files
committedOct 14, 2024·
Added code for quicksort.py and kruskal algorithm
1 parent e9e7c96 commit d65aecf

File tree

2 files changed

+136
-0
lines changed

2 files changed

+136
-0
lines changed
 

‎divide_and_conquer/quicksort.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Function to perform partition of the array
2+
def partition(arr, low, high):
3+
# Choose the last element as the pivot
4+
pivot = arr[high]
5+
6+
# Pointer for greater element
7+
i = low - 1 # index of smaller element
8+
9+
# Traverse through all elements
10+
for j in range(low, high):
11+
# If the current element is smaller than or equal to the pivot
12+
if arr[j] <= pivot:
13+
i = i + 1 # Increment the index of smaller element
14+
arr[i], arr[j] = arr[j], arr[i] # Swap
15+
16+
# Swap the pivot element with the element at i+1
17+
arr[i + 1], arr[high] = arr[high], arr[i + 1]
18+
19+
# Return the partition point
20+
return i + 1
21+
22+
# Function to implement Quick Sort
23+
def quick_sort(arr, low, high):
24+
if low < high:
25+
# Find the partition index
26+
pi = partition(arr, low, high)
27+
28+
# Recursively sort the elements before and after partition
29+
quick_sort(arr, low, pi - 1) # Before partition
30+
quick_sort(arr, pi + 1, high) # After partition
31+
32+
# Driver code to take user-defined input and sort
33+
if __name__ == "__main__":
34+
# Ask the user for input
35+
n = int(input("Enter the number of elements in the array: "))
36+
37+
# Input array elements from the user
38+
arr = list(map(int, input(f"Enter {n} elements separated by spaces: ").split()))
39+
40+
print("Original array:", arr)
41+
42+
# Call quick sort function
43+
quick_sort(arr, 0, len(arr) - 1)
44+
45+
# Print sorted array
46+
print("Sorted array:", arr)

‎graphs/kruskal.py

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# Class to represent a graph
2+
class Graph:
3+
def __init__(self, vertices):
4+
self.V = vertices # Number of vertices
5+
self.graph = [] # List to store graph edges (u, v, w)
6+
7+
# Function to add an edge to the graph (u -> v with weight w)
8+
def add_edge(self, u, v, w):
9+
self.graph.append([u, v, w])
10+
11+
# Utility function to find set of an element i (uses path compression)
12+
def find(self, parent, i):
13+
if parent[i] == i:
14+
return i
15+
return self.find(parent, parent[i])
16+
17+
# Function that does union of two sets of x and y (uses union by rank)
18+
def union(self, parent, rank, x, y):
19+
root_x = self.find(parent, x)
20+
root_y = self.find(parent, y)
21+
22+
# Attach smaller rank tree under the root of the high-rank tree
23+
if rank[root_x] < rank[root_y]:
24+
parent[root_x] = root_y
25+
elif rank[root_x] > rank[root_y]:
26+
parent[root_y] = root_x
27+
else:
28+
parent[root_y] = root_x
29+
rank[root_x] += 1
30+
31+
# Main function to construct MST using Kruskal's algorithm
32+
def kruskal_mst(self):
33+
# This will store the resultant Minimum Spanning Tree (MST)
34+
result = []
35+
36+
# Step 1: Sort all edges in non-decreasing order of their weight
37+
# If we are using a greedy algorithm, we need to sort the edges first
38+
self.graph = sorted(self.graph, key=lambda item: item[2])
39+
40+
# Allocate memory for creating V subsets (for the disjoint-set)
41+
parent = []
42+
rank = []
43+
44+
# Create V subsets with single elements
45+
for node in range(self.V):
46+
parent.append(node)
47+
rank.append(0)
48+
49+
# Number of edges in MST is V-1, so we will stop once we have V-1 edges
50+
e = 0 # Initialize result edges count
51+
i = 0 # Initialize the index for sorted edges
52+
53+
# Loop until MST has V-1 edges
54+
while e < self.V - 1:
55+
# Step 2: Pick the smallest edge and increment the index for the next iteration
56+
u, v, w = self.graph[i]
57+
i = i + 1
58+
59+
# Step 3: Find sets of both vertices u and v (to check if adding this edge will form a cycle)
60+
x = self.find(parent, u)
61+
y = self.find(parent, v)
62+
63+
# If adding this edge doesn't cause a cycle, include it in the result
64+
if x != y:
65+
result.append([u, v, w])
66+
e = e + 1 # Increment the count of edges in the MST
67+
self.union(parent, rank, x, y)
68+
69+
# Else, discard the edge (it would create a cycle)
70+
71+
# Print the constructed Minimum Spanning Tree
72+
print("Following are the edges in the constructed MST:")
73+
for u, v, w in result:
74+
print(f"{u} -- {v} == {w}")
75+
76+
# Example usage
77+
if __name__ == "__main__":
78+
V = int(input("Enter the number of vertices: ")) # Ask user for the number of vertices
79+
E = int(input("Enter the number of edges: ")) # Ask user for the number of edges
80+
81+
g = Graph(V) # Create a graph with V vertices
82+
83+
# Ask user to input the edges in the format u v w
84+
print("Enter each edge in the format: vertex1 vertex2 weight")
85+
for _ in range(E):
86+
u, v, w = map(int, input().split()) # Take input for edge (u, v) with weight w
87+
g.add_edge(u, v, w)
88+
89+
# Print the constructed MST
90+
g.kruskal_mst()

0 commit comments

Comments
 (0)
Please sign in to comment.