Trace
, or traceView2
,
will show the evaluations of the ordering function. It also confirms Lukas Lang's analysis of Ordering[list, 1, func]
.
One might try to infer the algorithm for n > 1
:
The first two steps are the same as Lukas points out for n = 1
. From this point, the difference will be that Ordering
will construct a complete order instead of just finding the "minimum" (according to the ordering function). Thus the third step completes the order of {1, 2, 0.1}
by comparing the last pair of the first three elements, 0.1
and 1
.
The next two steps construct a partial order of the remaining three elements, and the 6th step completes the order of {0, -2, 3}
.
The last step compares the maximal element of {1, 2, 0.1}
and the minimal element of {0, -2, 3}
, which completes the order of all the elements.
As Lukas has mentioned, if the ordering function satisfied the conditions for an ordering function (for instance, the transitive property), there is no need to compare further pairs of elements. In this case, if the list of numbers is shuffled, you can get different results.
Code:
Manipulate[
Grid[{{
Labeled[
Graph[vv, Take[cmps, steps],
VertexLabels ->
Thread[vv -> Thread[Subscript[vv, Range@Length@vv]]],
EdgeLabels ->
Take[Thread[cmps ->
(Framed[Style[#, Red], Background -> LightBlue] & /@
Range@Length@cmps)], steps],
ImagePadding -> 20, ImageSize -> {350, 350}],
Row[{"Next: ",
ReplacePart[RotateLeft@cmps, -1 -> "End"][[steps]]}],
Top],
Column[{" Steps "}~Join~Take[cmps, steps]]
}}, Alignment -> Top, Dividers -> Center],
{{n, 1}, {1, 2, 3, 4}, TrackingFunction -> (trackFN[#] &)},
{{steps, 1}, 1, Dynamic@Length[cmps], 1},
{{vv, {1, 2, .1, 0, -2, 3}}, None},
{{cmps, cmps}, None}, {{trackFN, trackFN}, None},
Initialization :> (
trackFN = Function[n1,
n = n1;
cmps = Reap[
Ordering[vv, n,
With[{res = If[#1 > 0, #1 < #2, False]},
If[res, Sow@DirectedEdge[#1, #2],
Sow[DirectedEdge[#2, #1]]]; res] &]
][[2, 1]];
steps = Length@cmps;
steps];
trackFN[1])
]