feat: Add topological sort and disjoint set algorithms#185
feat: Add topological sort and disjoint set algorithms#185Siddhram wants to merge 1 commit intoTheAlgorithms:masterfrom Siddhram:add-new-algorithm
Conversation
There was a problem hiding this comment.
Pull Request Overview
This PR implements two fundamental graph algorithms in R: topological sort using Kahn's algorithm and a disjoint set (Union-Find) data structure. These algorithms provide efficient solutions for dependency resolution and connectivity problems with optimized time complexities.
- Topological sort implementation for finding linear ordering of vertices in directed acyclic graphs
- Disjoint set data structure with path compression and union by rank optimizations
- Comprehensive test cases and examples demonstrating real-world applications
Reviewed Changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
| graph_algorithms/topological_sort.r | Implements Kahn's algorithm for topological sorting with cycle detection and test cases |
| graph_algorithms/disjoint_set.r | Implements Union-Find data structure with path compression and union by rank optimizations |
Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.
| if (ds$parent[v + 1] != v) { | ||
| # Path compression: Make all nodes on path point to root | ||
| ds$parent[v + 1] <- find_set(ds, ds$parent[v + 1]) | ||
| } | ||
| ds$parent[v + 1] |
There was a problem hiding this comment.
The find_set function modifies ds$parent but doesn't return the updated data structure. In R, modifications to list elements inside functions don't persist unless the modified object is returned and reassigned.
| find_set(ds2, 3) # This should compress the path | ||
| cat("Parents after find:", paste(ds2$parent, collapse = " "), "\n") |
There was a problem hiding this comment.
The path compression demonstration won't work as expected because find_set doesn't modify the original ds2 object. The parent array will remain unchanged after the find_set call.
Implemented Graph Algorithms in R
Topological Sort (Kahn's Algorithm)
Finds a linear ordering of vertices in a directed acyclic graph (DAG).
Detects cycles and resolves dependencies efficiently.
Time Complexity: O(V + E)
Space Complexity: O(V) for adjacency list and queue.
Includes examples for task scheduling and dependency resolution.
Disjoint Set (Union-Find)
Efficiently performs set operations using path compression and union by rank.
Supports find_set and union_sets operations for connected components and network connectivity.
Time Complexity: Near O(1) amortized per operation
Space Complexity: O(N) for parent and rank arrays.
Includes examples demonstrating graph connectivity and merging operations.
Both implementations include: