user2896551
user2896551

Reputation: 161

Randomly sorting (by fulfilling some conditions)

I'm looking for an algorithm that can make a random sorting but by fulfilling some conditions.

For example:

List: {1,2,3,4,5,6,7,8,9}

Conditions: {(4 before 8), (6 before 1), (3 before 2)}

So in the random sort of the list number 4 must be before number 8 and so on...

I need this in Java (with ArrayList) but I can't find an algorithm to do it! If anybody knows an algorithm that does this thing please write the name of Algorithm in answer or if you have a clue how to solve it a little explanation would be nice.

Upvotes: 1

Views: 160

Answers (1)

Rob Neuhaus
Rob Neuhaus

Reputation: 9290

You really want a topological sort. The conditions are really edges in a graph, and the numbers are nodes. A topological sort will produce an order that preserves all the constraints.

Upvotes: 7

Related Questions