Skip to content

Rework Topological sort #481

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Apr 4, 2023
Merged

Conversation

aesteve
Copy link
Contributor

@aesteve aesteve commented Mar 29, 2023

Topological Sort, reworked

Description

I was reading through Kahn's algorithm and topological sort and got a bit confused by the existing implementation, notably by the visited set which is declared, written to, but never read from.

So I went ahead and rewrote it the following way:

  • use a Vec of pairs to describe the graph, rather than a BTreeMap
  • relax the constraint for Ord for Nodes, and use Hash+Eq instead, using a HashMap instead of a BTreeMap (it sounds a bit more usual to me, but that's definitely opened to discussions)
  • get rid of the visited set which wasn't used
  • add a check at the end of the algorithm to check if we have visited every node,
    • if so, return the topologically sorted nodes
    • if not, return an Error (=> means the algorithm now detects cycles, and doesn't only partially sort)
  • I've added some tests, one coming from the Wikipedia page on topological sort, the other being a cyclic graph

Definitely open to discussions about the implementation and/or changes I've made. No problem, I mostly did this for learning purposes.

Type of change

Please delete options that are not relevant.

  • Breaking change since I changed the API a bit.

Checklist:

  • I ran bellow commands using the latest version of rust nightly.
  • I ran cargo clippy --all -- -D warnings just before my last commit and fixed any issue that was found.
  • I ran cargo fmt just before my last commit.
  • I ran cargo test just before my last commit and all tests passed.
  • I checked COUNTRIBUTING.md and my code follows its guidelines.

@aesteve aesteve requested review from siriak and imp2002 as code owners March 29, 2023 08:19
@aesteve aesteve changed the title Topological sort Rework Topological sort Mar 29, 2023
Copy link
Member

@siriak siriak left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, thanks!

@siriak siriak merged commit 83f9d4a into TheAlgorithms:master Apr 4, 2023
aesteve added a commit to aesteve/algorithms-in-rust that referenced this pull request Apr 4, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants