0

I am looking for an algorithm that can do sorting with requirements. As an example if I have 3 nodes N1, N2 and N3 I have the requirement that N2 must come after N3, and N3 have the requirement that it must come after N1. So the correct sort will be N1, N3, N2.

1

1 Answer 1

5

Form a graph from your requirements. Your items are the nodes and there is a directed edge from A to B if A must come before B. Repeatedly, remove a node that has no incoming edges and remove all of its outgoing edges. Do this until you have removed all the nodes. You will have removed them in the desired order, satisfying the requirements.

For the details of the implementation, see here: Topological sorting.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.