# Derivative of Sort

I want to calculate gradient of Sort[{x1,x2,x3,x4}] but it seems like I'm getting a wrong answer. Specifically Plot[Sort[{2, 1, x, 10}][[4]], {x, -20, 20}] gives me

while D[Sort[{2,1,x,10}],x] returns {0,0,0,1}, which is not true.

Is there a way to fix it?

• Since Sort[{2, 1, x, 10}] yields {1, 2, 10, x} and the derivative of {1, 2, 10, x} is {0, 0, 0, 1}, I'd say the derivative is correct. What do you think it should be? – Michael E2 Jul 20 at 22:48
• As for the Plot[], since it holds its argument, it won't sort {2, 1, x, 10} and then plug in x; instead, it plugs in x and then sorts (then takes part 4, which will be the greatest of the four numbers. -- I'm not sure which order of operations (plug in then sort or the reverse) you want. Max[{2,1,x,10}] might be a better way to approach it. – Michael E2 Jul 20 at 22:51
• Derivative is HevysideTheta(x-10) as you can see from the graph. – stiv Jul 20 at 22:52
• Try D[Max[{2, 1, x, 10}], x]. – Michael E2 Jul 20 at 22:53
• Max is a different function, which works, Sort doesn't. I need to differentiate Sort, not Max. – stiv Jul 20 at 22:56

Treating Sort as a function from the disjoint union of $$\bf R^n$$, $$n=0,1,2,\dots$$, to the same union, here is one way to define the derivative. I'll call the numerical sort NSort, just so I don't have to overwrite a built-in function.

NSort[list_?(VectorQ[#, NumericQ] &)] := NumericalSort[list];

Derivative[orders_List][NSort][list_List] /; Length[orders] == Length[list] :=
With[{args = Array[Slot, Length@orders]},
Evaluate@Piecewise[
Function[
p, {D[p, Sequence @@ Transpose@{args, orders}],
Less @@ p}] /@ Permutations[args],
Indeterminate
] & @@ list]


OP's example:

df = D[NSort[{2, 1, x, 10}], x]


Plot[Indexed[df, 4], {x, -20, 20}]


Another example:

D[NSort[{2, 1, 3 x, x^2}], {x, 2}] // PiecewiseExpand


• COOL! Thank you so much! – stiv Jul 21 at 1:58
• @stiv You're welcome. – Michael E2 Jul 21 at 3:10

Although this is definitely an XY problem, here is a possible solution:

list = {2, 1, x, 10};
listDer = D[list, x];

Plot[
listDer[[Ordering[list, -1]]]
, {x, -20, 20}
]


• This seems likely but the insistence on avoid Max makes me think the OP is interested in other components of the sorted vector as well. – Michael E2 Jul 21 at 0:39
• @MichaelE2 Yeah, probably. That's easy though: just drop the -1 in Ordering. Hard to tell what exactly OP wants anyway. – AccidentalFourierTransform Jul 21 at 0:45