# Reliably Broken Sort

Given a list of positive integers that contains at least 3 distinct entries, output a permutation of that list that isn't sorted in ascending or descending order.

### Examples

1,2,3 -> 2,1,3 or 3,1,2 or 1,3,2 or 2,3,1
1,2,3,3 -> 2,1,3,3 or 3,1,2,3 or 1,3,2,3 etc..


Thanks @Arnauld and @NoOneIsHere for the title!

• Will the input always be sorted? – xnor Aug 13 '17 at 20:31
• Must the sort be "reliable" in that given a given set of entries, it always produces the same permutation as output? Or must it only be "reliable" in that the output is not sorted? – Wildcard Aug 15 '17 at 3:16
• It must just satisfy the specs. – flawr Aug 15 '17 at 14:58
• Would a nested array be allowed as output? e.g., [2,[1,3]]. – Shaggy Aug 19 '17 at 9:51
• No, it should be one single array/list. – flawr Aug 19 '17 at 11:47

# JavaScript (ES6), 39 34 bytes

a=>[a.sort((x,y)=>x-y).pop(),...a]


Sort the array in ascending order, pop the last element and use it as the first element of a new array. Then destructure the remaining elements of the original array into the new array (In JS, both sort and pop modify the original array).

## Test it

o.innerText=(f=

a=>[a.sort((x,y)=>x-y).pop(),...a]

)(i.value=[1,2,3]);oninput=_=>o.innerText=f(i.value.split,)
<input id=i><pre id=o>

• Why cant you just do a.sort()? – geokavel Aug 14 '17 at 14:47
• @geokavel: Because JS's sort method sorts lexicographically. – Shaggy Aug 14 '17 at 14:50
• So because it's already unreliably broken? =D – jpmc26 Aug 15 '17 at 4:12

# Brachylog, 2 bytes

o↻


Try it online!

or

o↺


Try it online!

Sorts then rotates the list

# Jelly, 3 bytes

Ṣṙ1


Try it online!

• Ṣṙ- also works (just felt like saying that; you probably knew :P) – HyperNeutrino Aug 13 '17 at 20:05
• @HyperNeutrino Yep that works too, same bytecount :p – Erik the Outgolfer Aug 14 '17 at 7:43
• In which encoding is Ṣṙ1 only three bytes? In UTF-8, it's 7 bytes. – heinrich5991 Aug 15 '17 at 0:46
• @heinrich5991 Jelly uses a custom codepage. – cole Aug 15 '17 at 0:54
• I feel like everyone who uses Jelly must have a browser extension which adds a button to automatically post the "Jelly uses a custom codepage" comment. – 12Me21 Oct 21 '17 at 5:13

# Ohm, 2 bytes

S╙


Try it online!

Sort and rotate to the right.

# Japt, 3 bytes

n é


Test it

Sorts (n) the array and rotates it (é) one element to the right.

# Python 3, 31 bytes

lambda a:sorted(a)[1:]+[min(a)]


Try it online!

-1 byte thanks to xnor

• ...How did I not see this basic logic. >.> – totallyhuman Aug 13 '17 at 20:02
• @totallyhuman lol all 3 of my answers do the exact same thing. but ha :P Also I merged your PR for iOS -> MacOS :P – HyperNeutrino Aug 13 '17 at 20:02
• Yeah, I noticed and deleted my branch. :P – totallyhuman Aug 13 '17 at 20:04
• Putting the min at the end saves a byte. – xnor Aug 13 '17 at 20:11

# APL, 9 bytes

{1⌽⍵[⍋⍵]}


Try it online!

How?

⍵[⍋⍵] - sort the list

1⌽ - rotate by 1

• Also works in GNU and ngn! – Zacharý Aug 13 '17 at 20:32
• @Zacharý guess I'll just remove the dyalog... – Uriel Aug 13 '17 at 20:37

# TI-Basic (TI-84 Plus CE), 31 bytes

Prompt A
SortA(LA
max(LA→B
dim(LA)-1→dim(LA
augment({B},LA


Prompts for input in the format {1,2,3,4}.

TI-Basic is a tokenized language, all tokens used here are one-byte.

Explanation:

Prompt A         # 3 bytes, store user input in LA
SortA(LA         # 4 bytes, sort LA ascending
max(LA→B         # 6 bytes, save the last value in the sorted list to B
dim(LA)-1→dim(LA # 11 bytes, remove the last value from LA
augment({B},LA   # 7 bytes, prepend B to LA and implicitly print the result


# Pyth, 75 4 bytes

.P1S


Try it online!

-1 byte thanks to FryAmTheEggman

• You can save a byte by using permutations: pyth.herokuapp.com/… – FryAmTheEggman Aug 13 '17 at 20:52
• @FryAmTheEggman thanks, I'll update it when I get to a computer. – NoOneIsHere Aug 13 '17 at 21:13

# 05AB1E, 2 bytes

{Á


Try it online!

# 05AB1E, 2 bytes

{À


Try it online!

• – HyperNeutrino Aug 13 '17 at 20:03

# Retina, 21 bytes

O#
s(.*)¶(.*)
$2¶$1


Try it online! Sort and rotate as per usual. At least there's no unary conversion this time.

# Java 8, 68 37 bytes

l->{l.sort(null);l.add(l.remove(0));}


-31 bytes thanks to @Nevay (forgot Java 8 had a List#sort(Comparator) method..)

Modifies the input-ArrayList, instead of returning a new one.

Explanation:

Try it here.

l->{                   // Method with ArrayList parameter and no return-type
l.sort(null);        //  Sort the input-list (no need for a Comparator, thus null)
l.add(l.remove(0));  //  Remove the first element, and add it last
}                      // End of method

• You can use l->{l.sort(null);java.util.Collections.rotate(l,1);} to save 16 bytes. – Nevay Aug 14 '17 at 12:19
• Alternatively you can use l->{l.sort(null);l.add(l.remove(0));} to save 31 bytes (requires the usage of a not fixed sized list). – Nevay Aug 14 '17 at 12:24
• @Nevay nice one, but... the parentheses are a bit off in regards to the documentation: the reality is that the optional operations add and remove must be implemented; nothing is said about fixed-sized list... Kevin Cruijssen, given that there are much better alternatives in the previous comments, I'll wait for an edit before +1ing. – Olivier Grégoire Aug 14 '17 at 13:52

# Haskell, 36 37 bytes

import Data.List
f(a:b)=b++[a];f.sort


Use view patterns to match on the head of a sorted version of the input list, then append the first item of the list to the tail of the remaining list.

View patterns aren't worth it. Sort the list, take the head off, append it to the end. In this case, it turns out that the naive solution typed out compactly is the best.

• Welcome to PPCG! Great idea to use view patterns, I didn't know about them before. Unfortunately, they are not enabled in standard Haskell, so per site rules you need to include the bytes for the command line flag -XViewPatterns. Counting those the standard way f(a:b)=b++[a];f.sort is shorter. – Laikoni Aug 15 '17 at 18:57
• I somehow wasn't thinking about the flag needed. I guess I use them so much that I forgot that I turn it on in my Cabal files and that it's not part of the language. – typedrat Aug 16 '17 at 19:37

# Perl 6,  43  19 bytes

{first {![<=]($_)&&![>=]$_},.permutations}


Try it

*.sort[1..*,0].flat


Try it

Note that [1..*,0] would result in ((2,3),1), so .flat is there to turn it into (2,3,1)

# Mathematica, 18 bytes

RotateLeft@Sort@#&


Try it online!

• Shorter: RotateLeft@*Sort – JungHwan Min Aug 14 '17 at 3:46

# Ly, 7 bytes

&nasprl


Try it online!

Ugh, ruining the sort is so expensive!

Explanation:

&nasprl

&n      # take input as a list of numbers
a     # sort
sp   # save top of stack and pop
r  # reverse stack
l # load saved item


# R, 3332 29 bytes

Takes input from stdin. Sorts the list and then moves the first element to the end, ensuring that it is no longer sorted. Saved three bytes due to Giuseppe.

c(sort(x<-scan())[-1],min(x))


Another implementation, same byte count:

c((x<-sort(scan()))[-1],x[1])

• c(sort(x<-scan())[-1],min(x)) is 29 bytes using essentially the same idea as yours. – Giuseppe Aug 29 '17 at 21:15

# Ohm, 2 bytes

S╜


Try it online!

I think this is dissimilar enough from totallyhuman's post to post a new answer; I hope you don't mind :P EDIT: DAMMIT YOU NINJA'D ME

• Ninja'd you. ;) – totallyhuman Aug 13 '17 at 20:11

# Python, 31 bytes

def f(a):a[1:]=a[a.sort():0:-1]


Yet another Python solution.

Sadly, this one has the same length to HyperNeutrino's answer.

# Gaia, 3 bytes

ȯ1«


Try it online!

Same as other answers: sort ȯ and rotate left once 1«.

# Retina, 10 bytes

O#
O^#-2


Try it online!

O#     Sort the list
O^#-2  Reverse sort the list other than the last element


This leaves the list with the 2nd highest element first and the highest element last which is never correctly sorted

# Ruby, 18 bytes

Submitted on mobile. Please don't kill me for problems.

->a{a.sort.rotate}


# Pyth, 5 bytes

.>SQ1


# Explanation

SQ - sort input list

.>SQ1 - rotate input list cyclicaly by 1

# Proton, 19 bytes

a=>sorted(a)[1to,0]


Try it online!

-2 bytes indirectly thanks to xnor

Not yet working on TIO; waiting for a pull.

# Python 3, 28 bytes

lambda a:a[1:a.sort()]+a[:1]


Try it online!

a.sort() sorts a in place and returns None. None can be used as a slicing index and is the same as omitting that index.

# Python 3, 31 bytes

lambda a:a.sort()or[a.pop(),*a]


Inspired by Shaggy's JS answer.

# RProgN 2, 2 bytes

§›


Try it online!

# PHP, 44 bytes

requires PHP 5.4 or later for short array syntax.

sort($a=&$argv);print_r([array_pop($a)]+$a);


sort arguments, replace 0-th argument with removed last argument, print.
Run with -nr or try it online.

The 0-th argument is the script file name, "-" if you call PHP with -r. "-" is compared to the other arguments as a string, and since ord("-")==45, it is smaller than any number. The numbers themselves, although strings, are compared as numbers: "12" > "2".

php -nr '<code>' 3 4 2 5 1 and sort($a=&$argv) lead to $a=["-","1","2","3","4","5"] [array_pop($a)]+$a is [0=>"5"]+[0=>"-",1=>"1",2=>"2",3=>"3",4=>"4"], which results in [0=>"5",1=>"1",2=>"2",3=>"3",4=>"4"]. • Can you explain why [array_pop($a)]+$a doesn't overwrite the 0th index of$a? For example: $a=[1,2,3,4,5], array_pop($a) = 5, $a=[1,2,3,4]. If you do [5]+[1,2,3,4], shouldn't it end up being [5,2,3,4] because both arrays have a 0th index? I'm confused because the PHP manual says "The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored." – jstnthms Aug 14 '17 at 23:08 • @jstnthms The + operator does not append, it merges (without reordering the indexes; but that doesn´t matter here). The important point is that $a points to $argv and $argv[0] contains the script´s file name, the arguments start at index 1. I extended the description. Thanks for the question. – Titus Aug 15 '17 at 7:49

# Julia, 23 bytes

f(x)=sort(x)[[2:end;1]]


Slightly shorter than, but equivalent to f(x)=circshift(sort(x),1). I wish I could makeamethod based on select that was more, compact but I can not