I have a list of elements to sort and a comparison function cmp(x,y)
which decides if x
should appear before y
or after y
. The catch is that some elements do not have a defined order. The cmp
function returns " don't care ".
Example: Input: [A,B,C,D]
, and C > D
, B > D
. Output: many correct answers, eg [D,C,B,A]
or [A,D,B,C]
. All I need is one output from all possible outputs..
I was not able to use the Python's sort
for this and my solution is the old-fashioned bubble-sort to start with an empty list and insert one element at a time to the right place to keep the list sorted all the time.
Is it possible to use the built-in sort
/ sorted
function for this purpose? What would be the key?
It's not possible to use the built-in sort for this. Instead, you need to implement a Topological Sort .
The built-in sort method requires that cmp
imposes a total ordering . It doesn't work if the comparisons are inconsistent. If it returns that A < B one time it must always return that, and it must return that B > A if the arguments are reversed.
You can make your cmp
implementation work if you introduce an arbitrary tiebreaker. If two elements don't have a defined order, make one up. You could return cmp(id(a), id(b))
for instance -- compare the objects by their arbitrary ID numbers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.