Sort a list in a descending order

1

Say we have a list:

{{1/2, -(Sqrt[3]/2)}, {1, 0}, {1/2, Sqrt[3]/2}, {-(1/2), Sqrt[3]/2}, {-1, 0}, {-(1/2), -(Sqrt[3]/2)}}

now we want to sort that list by looking at the second component of each sub list (call it y coordinate for ease), i.e. sort it s.t. y is in the descending order. So we'd get

{{1/2, Sqrt[3]/2},{-1/2, Sqrt[3]/2},{1,0},{-1,0},{1/2,-(Sqrt[3]/2)},{-1/2,-(Sqrt[3]/2)}}

And yeah, I should mention that if there are more than one sub lists with equal y, we would additionally (sub)sort them by descending x (first component in each of the sub lists).

I tried to use SortBy, in different forms, but I don't seem to be able to figure it out by myself. I'd appreciate any help.

amator2357

Posted 2019-02-13T13:54:56.357

Reputation: 1 254

2"I tried to use SortBy" What did you try, specifically? – Szabolcs – 2019-02-13T13:57:29.007

2

Likely a duplicate of https://mathematica.stackexchange.com/q/2729/12

– Szabolcs – 2019-02-13T13:59:01.003

Thanks for that link @Szabolcs. Reverse[SortBy[list, N[Last]]] seems to be doing the job. – amator2357 – 2019-02-13T14:12:59.867

Not sure why and how in the case of those sub lists that have equal y component it puts those with the greater x first... – amator2357 – 2019-02-13T14:18:33.587

Just realized that Reverse[SortBy[list, N[Last]]] doesn't actually work. – amator2357 – 2019-02-13T14:24:56.843

3Try SortBy[list, N[-Last[#]]&] instead. – Sjoerd Smit – 2019-02-13T14:25:53.790

1You did not say what you tried originally. N[Last] is not a function, so it's not appropriate here. Use N@*Last or N[Last[#]]&. – Szabolcs – 2019-02-13T14:26:05.210

1@amator, if you've figured it out from the comments, you can answer your own question. Helps the silent majority of lurkers develop their knowledge too. – MikeY – 2019-02-13T14:51:43.460

Answers

1

As suggested in the comments, the following works as desired:

Reverse[SortBy[list, N[Last[#]]&]].

amator2357

Posted 2019-02-13T13:54:56.357

Reputation: 1 254

1If you use SortBy, you might as well put a minus sign in front of the sorting function so you don't have to reverse the list after sorting it. – Sjoerd Smit – 2019-02-13T16:13:05.960

Nice, wasn't aware of that, thank you @SjoerdSmit ! – amator2357 – 2019-02-13T16:14:11.807