[Question]
  [
Inspired by [this StackOverflow post](https://stackoverflow.com/q/70508442/7742131)
Given a list where each element appears a maximum of 2 times, we can define it's "sortedness" as the sum of the distances between equal elements. For example, consider
```
[1,1,2,3,3] (array)
 0 1 2 3 4  (indices)
```
The sortedness of this array is \$2\$. The distance between the `1`s is \$1 - 0 = 1\$, the distance between the `2`s is \$2 - 2 = 0\$ (as there's only one `2`) and this distance between the `3`s is \$4 - 3 = 1\$. Summing these distances, we get the sortedness as \$1 + 0 + 1 = 2\$.
Now, consider
```
[1,3,2,1,3] (array)
 0 1 2 3 4  (indices)
```
The sortedness of this array is \$6\$:
* `1`s: \$3 - 0 = 3\$
* `2`s: \$2 - 2 = 0\$
* `3`s: \$4 - 1 = 3\$
* \$3 + 0 + 3 = 6\$
In fact, \$6\$ is the maximal sortedness of the permutations of this particular array, and there are 16 permutations of `[1,1,2,3,3]` with a sortedness of \$6\$.
```
[1, 3, 2, 1, 3]
[1, 3, 2, 3, 1]
[1, 3, 2, 1, 3]
[1, 3, 2, 3, 1]
[1, 3, 2, 1, 3]
[1, 3, 2, 3, 1]
[1, 3, 2, 1, 3]
[1, 3, 2, 3, 1]
[3, 1, 2, 1, 3]
[3, 1, 2, 3, 1]
[3, 1, 2, 1, 3]
[3, 1, 2, 3, 1]
[3, 1, 2, 1, 3]
[3, 1, 2, 3, 1]
[3, 1, 2, 1, 3]
[3, 1, 2, 3, 1]
```
---
Given a list of positive integers, where each integer appears either once or twice, output a permutation of this list where the sortedness is maximal. You may input and output in any [convenient manner](https://codegolf.meta.stackexchange.com/q/2447/66833), and you may output any number of the permutations with maximal sortedness.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Test cases
```
input -> output
[1] -> [1]
[8, 7] -> [8, 7]
[1, 1, 2] -> [1, 2, 1]
[9, 7, 4] -> [9, 7, 4]
[2, 9, 3, 10] -> [2, 9, 3, 10]
[4, 4, 10, 10] -> [4, 10, 4, 10]
[1, 1, 2, 3, 3] -> [1, 3, 2, 1, 3]
[2, 8, 5, 6, 5] -> [5, 2, 8, 6, 5]
[5, 2, 6, 1, 9] -> [5, 2, 6, 1, 9]
[7, 1, 1, 4, 5, 5, 8] -> [1, 5, 7, 4, 8, 1, 5]
[3, 1, 2, 8, 3, 10, 8] -> [3, 8, 1, 2, 10, 3, 8]
[1, 1, 2, 2, 3, 3, 4, 4] -> [1, 2, 3, 4, 1, 2, 3, 4]
[4, 4, 3, 3, 2, 2, 1, 1] -> [4, 3, 2, 1, 4, 3, 2, 1]
```
  
[Answer]
# [Python 3](https://docs.python.org/3/), 47 bytes
```
lambda l:(sorted({*l},key=l.count)*2)[-len(l):]
```
[Try it online!](https://tio.run/##PU7dDoIgFL7vKbgERy3E/80nMS8scboInWHNtZ6djkCyM873c84H06r7UXHTlRcjm8e1bZAs8HOctWjxJ5BfehdrKU@3cVGaBCGpjlIoLElRm3c/SIFYMc2D0rjD4tVIPKhp0ZjAMRWrD1VGUQqNUQQVAspBoCgCFFIEhINzBhaBuEFP/YL1uRuGqJiiBG7gsTUTO5UDTy1iNiS2lYHK/ymZf8jJe7jPt1vR/gknOXsbrX8 "Python 3 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 57 bytes
```
lambda l:[x for c in 1,2,1for x in set(l)if l.count(x)-c]
```
[Try it online!](https://tio.run/##PY7bDoMgEETf@xX7KAltCt5N@iXWB2slklA0FlP79XS51ITAnJllYPmaadbcitvdqv71ePagmnYHMa8wgNTAKKfM0e7oPZpEESlAXYZ50ybZyXno7GeSagTWLKvUBkQi9bKZhBDbsu7UVhRKPBjFMuCoajQoZKg4BYQUkytShqaTEeMFn6dhGKtyCgXuyLkPCz9VI5deMV@S@1Whm/5bqvhQsI/y2O9vZccnghViN9r9AA "Python 2 – Try It Online")
Iterates through the distinct elements of `l` 3 times, first outputting those that appear twice in `l`, then those that appear once, then twice again.
*-1 byte by att*
# [Python 3.8](https://docs.python.org/3.8/), 47 bytes
```
def f(l):*map(l.remove,s:={*l}),;l+=[*s-{*l}]+l
```
[Try it online!](https://tio.run/##PU7dCoMgFL7fU3ip5cbM/qMniS6CGQVWUq01xp7dndQFB/3@zqfqvXbTyFM1a/0QLWqxJLk3NArL2yyGaRN0ycuPJ7@EFtIvK2@5Hqz2pX51vRSI5XsptkbiflTPFRNStHgnhZr7cQWgK1ZfqpSiBC5GEUwAKAOBohBQQBEQDs4dWAjiAR11C8bnNgxVEUUxnMAjY8YmlQFPDGKmJDKTgsr/Lal7yMpnues3W@H5CStZ@4jWPw "Python 3.8 (pre-release) – Try It Online")
*-3 bytes by pxeger with modifying the list in place*
[Answer]
# [J](http://jsoftware.com/), 10 bytes
```
/:~:*1#.e.
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqNgoGAFxLp6Cs5BPm7/9a3qrLQMlfVS9f5r/k9TMFKwUDBVMFMw5UpTMFcwBLJNgNhQwQLINwSyjRSMoaQhAA "J – Try It Online")
I had this first, hoping J might tie caird's Jelly, but I couldn't find any actual 9-byter.
### How it works
```
/:~:*1#.e.    Monadic train, input: X, a numeric vector
     1#.e.    Count occurrences of each number of X in X
  ~:*         Multiply with nub sieve (1 if a number appears first, 0 otherwise)
              First occurrence of a double becomes 2, second becomes 0
              A single becomes 1
/:            Sort X by the above
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 bytes
```
ReverseSort@Gather@#~Flatten~{2,1}&
```
[Try it online!](https://tio.run/##NY0xD4IwFIR3/gYJ05lYaKEMGiZdjYzGoSElkggmtXEh8Nfre0Wn3t13vTca/7Cj8UNnQn8IV/ux7m3bl/PNmZFr0vX0NN7baZ1ziCULFzdM/pbujn2T3rO17QyhZBYLklmj4kdAIGdRo4JkkaNGAbFnLSFJ/UysEiq2loZCCcVGUV4SrdlU4KIkqqA5KOI/HUe3ZFuKW1SU/0tsOSa8JEv4Ag "Wolfram Language (Mathematica) – Try It Online")
```
                   #                    {1,1,2,3,3}
            Gather@                     {{1,1},{2},{3,3}}
ReverseSort@                            {{3,3},{1,1},{2}}
                    ~Flatten~{2  }      {{3,1,2},{3,1}}
                               ,1       {3,1,2,3,1}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ẹⱮ_"JỤị
```
[Try it online!](https://tio.run/##y0rNyan8///hrp2PNq6LV/J6uHvJw93d/w@3P2pa4/7/f7RhrI5CtIWOgjmINtRRACIjJKaOgjEQgQSMYQIWYDFDAyALRSFUrY6CCRDFAgA "Jelly – Try It Online")
### How it works
```
ẹⱮ_"JỤị    Monadic link. Input: X, a numeric vector
ẹⱮ         For each element n of X, get all indices of n in X
  _"J      For each list of indices, subtract the original index
           If n appears twice, the first becomes [0, positive],
           and the second becomes [negative, 0].
           If n appears only once, it becomes [0].
     Ụị    Sort X by the above
           All [negative, 0]s come first, then [0]s, then [0, positive]s
```
I really hope Jelly were a proper derivative of J/K, in which case we wouldn't need the `"`.
[Answer]
# [Factor](https://factorcode.org/), ~~94~~ 62 bytes
```
[ [ ] collect-by values [ length ] inv-sort-with round-robin ]
```
Have a screenshot of running this in Factor's REPL because `collect-by` postdates the build on TIO.
[![enter image description here](https://i.stack.imgur.com/n0UX6.png)](https://i.stack.imgur.com/n0UX6.png)
## Explanation
I finally found a use for `round-robin`! It's sort of like if `flip` (matrix transposition) worked for non-rectangular matrices and it also flattens the results.
```
                          ! { 1 1 2 3 3 }
[ ] collect-by            ! H{ { 1 V{ 1 1 } } { 2 V{ 2 } } { 3 V{ 3 3 } } }
values                    ! { V{ 1 1 } V{ 2 } V{ 3 3 } }
[ length ] inv-sort-with  ! { V{ 1 1 } V{ 3 3 } V{ 2 } }
round-robin               ! { 1 3 2 1 3 }
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ĠEÞZFị
```
A monadic Link accepting and returning a list of positive integers as specified.
**[Try it online!](https://tio.run/##y0rNyan8///IAtfD86LcHu7u/n90z@H2R01rjk56uHMGkAaiLBDVMEdB107hUcPcyP//o6MNY3UUoi10FMxBtKGOAhAZITF1FIyBCCRgDBOwAIsZGgBZsbEA "Jelly – Try It Online")**
### How?
Produces a list of the form `a+b+a` where `a` is a list of the elements that are present twice and `b` is a list of the elements that only appear once. (`a` and `b` are also each sorted by value as a side effect of the method employed.)
```
ĠEÞZFị - Link: list of integers with at most two of each, A
                                             e.g. [3, 3, 1, 1, 2]
Ġ      - group indices of A by their values       [[3, 4], [5], [1, 2]]
  Þ    - sort the result using:                    v       v    v
 E     -   all equal?                              0       1    0
                                              ->  [[3, 4], [1, 2], [5]]
   Z   - transpose                                [[3, 1, 5], [4, 2]]
    F  - flatten                                  [3, 1, 5, 4, 2]
     ị - index back into A                        [1, 3, 2, 1, 3]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 8 bytes
```
Œ!ĠISƊÐṀ
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLFkiHEoElTxorDkOG5gCIsIiIsIiIsWyIxLCAxLCAyLCAyLCAzLCAzIl1d)
[Answer]
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 17 bytes
```
cx<tx<rsB l<gr<sr
```
## Explanation
This one is pretty simple, it composes 5 functions:
* `sr` sorts a list.
* `gr` groups a list into contiguous sublists of equal elements.
* `rsB l` sorts a list of lists in descending order of length.
* `tx` transposes a list of lists.
* `cx` concats a list of lists.
## Worked example
We take the original list:
```
1 2 9 9 3 1
```
... sort it
```
1 1 2 3 9 9
```
... group it
```
1 1
2
3
9 9
```
... sort by length
```
1 1
9 9
2
3
```
... transpose it
```
1 9 2 3
1 9
```
.. and concat it
```
1 9 2 3 1 9
```
## Reflections
This score seems pretty weak despite how straightforward the answer is. However I think there could be some improvements.
* `rsB l` and `sB l` could probably be their own functions. Sorting lists by length is likely to come up again so it would be nice to have these.
* `gr<sr` could probably be rolled into one function. It's not uncommon to want to get all the groups irrespective of the initial order and 5 bytes is a big price for that. Since the final order is arbitrary why not sort the output by size. It's the order we want here so that shows it's at least useful once.
As of [e7ce5325](https://gitlab.com/WheatWizard/haskell-golfing-library/-/commit/e7ce53255b667b951b99dc5899cdfa9dd9375b00)  these changes have been implemented saving 9 bytes:
```
cx<tx<bg
```
Obviously this is non-competing, but these changes should be helpful in the future.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
ÙΣ¢}RI∍
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8Mxziw8tqg3yfNTR@/9/tLGOgqGOgpGOgoWOAohtAGTFAgA "05AB1E – Try It Online")
-4 thanks to @ovs
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~14~~ ~~12~~ 9 bytes
```
9B#u1>&)y
```
The input is a column vector. The output contains each entry on a line (not necessarily right-aligned). [Try it online!](https://tio.run/##y00syfn/39JJudTQTk2z8v//aENrBSAyslYwBqJYAA) Or [verify all test cases](https://tio.run/##y00syfmf8N/SSbnU0E5Ns/K/QXKES8j/aMNYrmgLawVzIGVorQBERkCWJVDAWsEEyDKyVgByjIEyBkCeCVAQxIRyoRrA8sYQxUCjTK0VzIAkkG8KljQDq7IE8s3BLEOwIaZgZAEUNYaZYgG1CCIMNxxqPliXCdwRECGINEhpLAA).
### Explanation
This outputs the duplicated numbers in their original order, then the non-duplicated numbers, then the duplicated numbers in their original order again.
```
9B   % Push 9, convert to binary. Gives [1 0 0 1]
#    % Use as output specification for the next function
u    % Implicit input. "Unique" function, first and fourth outputs. This
     % pushes the unique numbers in their orignal order, and their count
1>   % Greater than 1? (element-wise). Gives a mask for duplicated numbers
&    % Use alternative output specification for the next function
)    % Indexing, two outputs. This pushes the duplicated numbers, then the
     % non-duplicated numbers
y    % Duplicate from below. Implicit display
```
[Answer]
# Python3, ~~139~~ ~~131~~ ~~116~~ 106 bytes
```
def f(x):
 l,m=[],[]
 while x:
  i=x.pop()
  if x.count(i):l+=[i];x.remove(i)
  else:m+=[i]
 return l+m+l
```
[Try it online](https://tio.run/##bZJRj4MgDMff/RR9lEjMOXRzXvgkxqcbZiQoBt3O@/Reqajb5RIC7b@/ltIw/Ex324tycMtyUy208cyqCAzvZN3wuong@66NghlF0HJOBzvEzNstzOmXffRTrFllElnr5nNOnersU6GEiDKjqjqKRODU9HA9mKRLzDKpcRpBQo0UQFxnDQfcGA9@yeHiJTp3NeOA60QsnugdsSuSHHIf28w9hiRqAvkPH391dybHDK9sUHDydyp0QNki9CHWVrzweiO2XnA44@65gqAyCDu3ymdKvx7cJuzchYSM@iloleH2Yn0s1c7eaout1zI8NiSJjT2tovf/eWF4JNXOj5GvwmH/naDYBrLOJAuz3Id02A2LmihqrQPNwYLugX5FReUGp/FjKagk/kjNEOBg9DjFTj2VG9UtVoyBlGDZ8gs)
## Alternative with lambda, 103 bytes
With non-deterministic ordering of elements. I'm not sure, whether that counts:
```
lambda x:(l:=[e for e in set(x)if x.count(e)>1])+[e for e in set(x)if x.count(e)<2]+l
```
[Try it online](https://tio.run/##hVLLboMwELz7K/ZoKzQqIQ@CSn4k5UCDUS0ZjMBU9OvT9dpAUlUqQrZ3dvap6b7tp2mTtOvvdf5@12XzUZUwZVxn@VVCbXqQoFoYpOWTUDVM25sZW8uluMSF2PzDedsVG32ve9PAzWgtb1aZdgDVdKa3UMm6HLWt1M0yZuVgB8jhygA/fo2LCPAQUbDTCE4OontB4wjw3xEXb7RW3xmZEeydb34uPmQiliD/1fkfzYWzxwiHzKRg7J9ZoQOKTkIfiW/FAY8VsfVDBEc8He9ApDQAC8/DRwo/r7wZWHgnAmLq50B/Gqof/LCUO37Kncy9pmHYEJTM3J0Hnf3HhGFIyr1fV@6B9f17g8m8EL@TOOxyWdL6LgQrGENZQKXqmmuRUaIKZfGgFa7VYAV5nPZU5OUn27GRfWnlEkexV1lsy66TbcWVD6Kjl3bsUbNjw5tywpCXRrV4UUrt8lXbr1KPcuACUNNakvcCsWCMhbrG8Ui4vmDXKyd7yHKosRoSIj@JFOFhhLj/AA)
[Answer]
# [Python 3](https://docs.python.org/3/), 69 bytes
```
def f(l):x={z for z in l if l.count(z)<2};y=[*{*l}-x];return y+[*x]+y
```
[Try it online!](https://tio.run/##HczBCoQgGEXhV7nLtBqYmlXlk4irKRnhR0MM1OjZHQu@5eHsKfycHQsJ@elQjY/h8a5UWTcN3RCbojgztPPIMBYEo0GvrztsaDJbhmtOQvKT09VHNfstHN4itZJH1aaye1O7@8PKHw "Python 3 – Try It Online")
No, @xnor has better version of this idea, heck @tsh has even better
[Answer]
# [J](http://jsoftware.com/), 19 bytes
```
/:~:]`(I.@[)`[}1#.=
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/9a3qrGITNDz1HKI1E6JrDZX1bP9rcvk56SnoW0Vbaes7aGiZ1GjrxygZatpqgWS5uFKTM/IV0hSMFAyB0FjBGCZgCGNYKJjDxYAKQAqN/wMA "J – Try It Online")
The idea is to create a mask for sorting, such that unique elements are pushed into the middle, and the first and second instances of repeat elements are pushed right and left, like a solution of water, oil, and mercury.
Consider `2 1 1 3 3`:
* `=` Creates boolean masks for each unique element:
```
1 0 0 0 0
0 1 1 0 0
0 0 0 1 1
```
* `1#.` Sums the rows:
```
1 2 2
```
* `~:` Nub sieve of input: ones at the first occurrence of each element:
```
1 1 0 1 0
```
* `]`(I.@[)`[}` Update the nub sieve `[` at the indices of those ones `(I.@[)` using the row-sum values `]` (ie, `1 2 2`):
```
1 2 0 2 0
```
* `/:` Sort the original input according to that:
```
1 3 2 1 3
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
Ｗ⁻θυ⊞υ⊟ιＦ³ＩΦυ¬﹪⁻ι№θκ²
```
[Try it online!](https://tio.run/##LYyxCsJAEER7v2LLXVhBTSOkDNhF0ocUR4zc4pE1d7f6@ecFnOox85jZuzirC6V8vYQFsJfVEm4MRgSDJY/GMOgbhag9PDUCNnWIsmbsXMp4k5CXuFt3zdjrw4L@X4ShU6tivXsRMVxoT1vKODYM51owXBl2PlWapnL8hB8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Since each element is guaranteed to occur no more than twice, the exercise reduces to printing the elements that are duplicated, then the ones that only appear once, then the ones that are duplicated again.
```
Ｗ⁻θυ⊞υ⊟ι
```
Create a (reversed) deduplicated list of elements.
```
Ｆ³ＩΦυ¬﹪⁻ι№θκ²
```
Output the elements three times, but alternately filtered on whether the element was originally duplicated or not.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes
```
ĠvḢf?Ġ'₃;fȮJJ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLEoHbhuKJmP8SgJ+KCgztmyK5KSiIsIiIsIlsxLDEsMiwzLDNdIl0=)
Wow this is a mess.
```
Ṗµ          ;t # Maximal permutation by...
  Uv=∩         # For each unique element, indices of equal elements?
      ƛ   ;∑   # Apply to each, taking the sum
       T       # Truthy indices
        ¯h     # Cumulative differences
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
ΣT↔ÖLk=
```
[Try it online!](https://tio.run/##yygtzv7//9zikEdtUw5P88m2/f//f7S5jiEQmuiYAqFFLAA "Husk – Try It Online")
Output is concatenation of:
1. List of all elements present, with those appearing twice coming first
2. List of elements that appear twice, in the same order as 1
```
     k=  # group list elements by equality
   ÖL    # and sort the groups by length
  ↔      # and reverse this order
         # (so now 2-element groups are first,
         # then 1-element groups),
 T       # now transpose
Σ        # and flatten the resulting list of 2 lists
```
[Answer]
# [R](https://www.r-project.org/), ~~55~~ 54 bytes
*Edit: -1 byte thanks to Giuseppe*
```
function(x)names(y<-table(x))[c(order(-y),which(y>1))]
```
[Try it online!](https://tio.run/##bc5NCsIwEAXgfU8xYBcJpIuKogvrRcRFjGkbiIlMJmpOX2P9BcvbDAPz5sMhuuCRmqGNTpHxjt24kycdWNpUJA9W5wXfKebxqJFViYtrb1TP0rbmfP86Z4qtRJ2zEMucNecAM/CRzpFABpCIMoFvIRAa14XHSL0Gj6YzTlrQVp@0o1AUz8J5U3xBIjWYHeOjjOGpvPyASvshlXZEvTsmVJOoP8VwBw "R – Try It Online")
Output as strings of the original elements. Add +3 bytes to output as the original elements themselves (see TIO link).
Output is: one of each element that appears twice, then elements that appear once, and finally one more of each element that appears twice.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/index.html), 13 bytes
```
(⍷⍒∘⊒⊸⊏˜)∾⊒⊸/
```
[Try it at BQN online REPL](https://mlochbaum.github.io/BQN/try.html#code=VW5zb3J0IOKGkCAo4o234o2S4oiY4oqS4oq44oqPy5wp4oi+4oqS4oq4LwoKVW5zb3J0IDfigL8x4oC/MeKAvzTigL814oC/NeKAvzg=)
```
         ∾      # join together:
(⍷⍒∘⊒⊸⊏˜)       # L: unique set of elements, with those present twice first
    ⊒           #    occurrence count of each element
  ⍒∘            #    reverse order (so those twice first)
      ⊸⊏˜       #    use this to index original elements
 ⍷              #    and deduplicate them;
          ⊒⊸/   # R: just the elements that are present twice
          ⊒     #    occurrence count of each element
           ⊸/   #    use this to select original elements
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes
```
Ṗµv=UvTv¯f∑;h
```
[Try It Online!](https://vyxapedia.hyper-neutrino.xyz/tio#WyIiLCLhuZbCtXY9VXZUdsKvZuKIkTtoIiwiIiwiIiwiWzEsMSwyLDJdIl0=)
Vyxal's deltas is negative for whatever reason, but no worries, we just get the minimum value then.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~53~~ 44 bytes
```
O$`(\d+)((?<=\b\1,.*))?((?!.*,\1\b))?
$#2$#3
```
[Try it online!](https://tio.run/##JYy9DsIwEIP3ewvUICXFqrj8NIkE6sjIC2QoFR1YGBDvHy5hOvuzz5/9@3o/6lHf1npXqy7Pk9F6uVzLVhjTaMwi9jCNKFw2caQGqwZXK1NCJAbDUkaEJ4sMBz6Th5fTVI8FOgkTAmYECkJm4ZkiWu6FByRyvZv6hNj/a3@Wiu@jTTcm2Q8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Saved 9 bytes by using @Bubbler's idea of encoding both whether the elements need to be sorted to the start or the end in the same sort key.
```
(\d+)
```
Matching each entry...
```
((?<=\b\1,.*))?
```
... check whether this is the second entry of a duplicate, and...
```
((?!.*,\1\b))?
```
... check whether this is a unique entry or the second entry of a duplicate.
```
O$`
$#2$#3
```
Sort by a combination of the two checks. The first entry of a duplicate has a sort key of `00`. Unique elements have a sort key of `01`. The second entry of a duplicate has a sort key of `11`. This means that the unique elements sort between the two sets of duplicate elements.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
A port of [tsh's Python answer](https://codegolf.stackexchange.com/a/240372/64121).
```
Qċ@Þ¹Uṁ
```
[Try it online!](https://tio.run/##y0rNyan8/z/wSLfD4XmHdoY@3Nn4/3D7o6Y17v//RxvG6ihEW@gomINoQx0FIDJCYuooGAMRSMAYJmABFjM0ALJQFELV6iiYAFEsAA "Jelly – Try It Online")
```
Q        -- the unique elements of the list
   Þ     -- sort by ...
 ċ@ ¹    --   the number of occurences in the full list 
     U   -- reverse
      ṁ  -- mold; reshape the list to the length of input by reusing from the front
```
[Answer]
# python3, ~~121~~ 101 bytes
```
def u(l):
 x=[]
 y=set()
 for i in l:x.append(i)if l.count(i)%2else y.add(i)
 y=list(y)
 return y+x+y
```
[Try it online!](https://tio.run/##PU7baoQwEH33K@alkLAi9bbrWvwS8UFqZAMhBk3a5OvtMdqFYXIuM2dign0tutz3SczkmOJtQr7rh4RCtwnLeELzspIkqUm1PhuNEXpiksuZVPa9OG1BPgqhNkEhG6fDO5aV3CwLgKuwbtUUbv4W9t@XVILy1nfiZ1RMauNwg3@ZVSLIMc/53udD0jcpPfDkKaEKoCeElCqgIiWQEs4nWAXxgBe9FqJfnsOIqlO6o4PX0bzHqSf4I6I8htSxGqjlf0pzHTrld/iVH7eq9ydO6bSP0eEP)
Thanks to caird coinheringaahing
[Answer]
# [Perl 5](https://www.perl.org/), 67 bytes
```
sub f{pop=~s/(.*)(\b\d+ )(.*)(\2)(.*)/my$x=$2;$x.f("$1$3$5").$x/er}
```
[Try it online!](https://tio.run/##dZRbb9owFMef609xlLl1srlJQwilQdl4X9W@bE8FRXQNVTZyWRwkKsS@OjvYuTgplQI5/vt3Lj74UMTlxj8exfYZ1vsiL8J/wjHtz5a5eF68fAFL2SP5dtI3ugvpaEZ39to0qEs96huWTXdOXB5kDJGXVfySxULAHtI3uCxy4c6Anl57Gj3RaHlwnJBGsM5LuLFt@imagdimZroqaHTdA7nat@BAkDYJwBPgx11C@FW@YMkbccrhVunK0vdcDviMaje0cN0n7tCHw1gR7UIn0Ad1Dz1vFNUTdHKMvie1Q@vl@D1bVybjeG19nipRSoMa8HA@hwl@K9qX6LSRdFptTWSgO51uJZ2@laIrq/TlM23r8VVDZB73XR6vOcO0bkfr6jUeIyV7cufs@esWyCxj/YdSUmef67XXtEx1zW273jays2t/a48hAG@oSZOs2FacrqJ0tSviMrXCOY1m9TbQWITdpTbnGtcxr3nVqCEOBsxVUDA6Zq4zotgkFQPGdU8tXD@lxtTxijLJqrVxeT0RuMJcQZsSAPGglw61GI1fGDDq4ganoym8r76KRWZwcoEGhKGkrq7gd55kJuOMn1izzmZZEP8dbunlWvANWP6HQQDs4fEHPH5nM3JBDmQrYrhPRBUEP6tkAwz/AdgRR5qo8SXtzJJ2HElv5Eh/zshglMhgWMjg7pOzF56cv8zko3tKPrqA/wE "Perl 5 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 48 bytes
```
function(x)c(d<-x[duplicated(x)],setdiff(x,d),d)
```
[Try it online!](https://tio.run/##K/pfmlecX1SiYKP7P600L7kkMz9Po0IzWSPFRrciOqW0ICczObEkNQUoFqtTnFqSkpmWplGhk6IJRFCtGska5jqGQGiiYwqEFpqa/wE "R – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 43 bytes
```
->l{(l&l-z=l.select{|x|l.count(x)<2})+z|=l}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6nWiNHLUe3yjZHrzg1JzW5pLqmoiZHLzm/NK9Eo0LTxqhWU7uqxjan9n@BQlp0tKGOkY6xjqGOcWwsF1jAREcBiIzByAiMDIEoNvY/AA "Ruby – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), 46 bytes
```
~a=(!x=a∩a[a.|>i->sum(i.==a)==x];[!2;!1;!2])
```
[Try it online!](https://tio.run/##TVBJboQwELz7Fc2cQAIUs8wwQuaeQ15gcehoSOSIOAgYiUM053wl38pHSGObBVm4qrrscvfHvVXIp3l@oPC9SeDfzy9KjL8rFVXD/dNXsRAYCDHVpfSS0uOll9TB/PbVgwKloW/w1irdDH7AgD4MX0HA0LVq9FV4iqqT00l91qN8aUaMO@yHxscgxv59KGtj6Hqlx1b7ZKzggQFr9G2WvIaoAtqYLEK4WGYQkzwEWolzECJO8pWqIWRWXgmTVCWSkufJlo4Ckxm5FrjXHc2cwaWZE@mWmdrYRTIR9LQ8hDP9rSU39cJJzPGzOXI9WlaJyYtB3CTnZhVbXG7bMTdye2O6vqtwzWz@dLUlVl74sRHXi7kvO07RSjvexpOuDdue@TaobQw7rv8B "Julia 1.0 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~119~~ \$\cdots\$ ~~103~~ 97 bytes
```
*b;*p;f(a,e)int*a,*e;{for(b=a;a<e;++a)for(p=a;++p<e;)*a==*p?*p^=*--e^(*e=*p),*a^=*b^(*b++=*a):0;}
```
[Try it online!](https://tio.run/##rVVbb5swFH7fr7AiVeIWDWOudVkfpv2KNJ0IdTq6jaCAtGgVf33ZwRdsk3Tqw6IEH5/vO1f7kHr9XNfns7ejXkf3ThUwt2kHrwo8Rl/3h6OzKyta3THq@5U77TvY@34HGterytLr7r3usfTWa/boeAz2buBVoNjBduf7pVe5tyEdz@AV/aya1nHR6wcEn0kxsH7Amy0q0Sse6ayKhCoPUGZoiSQGCL6RAcQCKIAeoNgAEgFEAQKMgF1ogKkAYzCZkAWaWcG4NTHgfPYMSSYBSuFpwIWAE26ach@FAeNQ4BlHMM9A@DGdYNkZonLIZREgmbRokarMlns1u4GJWbGgCPpkOlJ1Kh5n94LMDQNxKmIhYonFkoglFUsmllwsRSCrlav0g6UjTHRMrmhFyL75zQ57h1Pcj3LniW2ADDSy0chGiY0SG41tNLbRxEYTG01tNLXRzEYzG81tNLfRwkYLG8Xhoh3hAl@2a9EvvGgYXnQML1oGe@OE2Klj9cCeFvOq1JczqxA9txG/ZxZ4dXYV@Ob8KoKe4emSxVcYeo6JuupkQcnNYc2tWVaUf8zz3JZwjpSIYrgzfOnMmOtczeyUPtFzPVMjs3dipLW8JOv5nmvVsjnfykLwZ/tAH6YWiRZjLSZaTLWYaTHXYhEYTTJkIx42As6vhfrQ9gOqv1VHD56s/s6OIuHVw@lL9HAqPsMvWQXI3JOVtIb/KuRM7WnaJ3YCs5BK8U7deRVR3/pZQ5Hvc7bLnYl/LP1@BHfiHck5W2rCqJVoe4F2R8D3zmqzcrVSJyqThARbHt814prmN/3NE5Td3E@1367gOWyareFyvIi4RetPyA7rDGCHfNS61K6OQR7zDblWYH84AtSyvv/KeM5voYONvr/SmfkCzAaSxBREyX5ZsnnkPXIYdAGVkPzmZeteMKaPlblfgs81auhVZ4N0NrzH2fCGs/H/nd9N/9ACUw2CfQallYxyNX4Yz3/q/Y/quT@vf/0F "C (gcc) – Try It Online")
*Saved 3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
Inputs a pointer to an array of integers and a pointer one past the end of the array (because pointers in C carry no length info).  
Unsorts the array in place.
### Commented
```
*b;*p;f(a,e)int*a,*e;{             // declare pointers and f    
    for(   ;a<e;++a)               // main loop a to the end   
        b=a                        // init b to the beginning    
        for(p=a;++p<e;)            // inner loop of p from      
                                   //   a + 1 to the end
            *a==*p?                // is current int equal to  
                                   //   another int in a?    
                *p^=*  e^(*e=*p),  // then swap second int with  
                                   //   one before the end   
                     --            // move end back one    
                *a^=*b^(*b  =*a)   // and swap current int with   
                                   //   the beginning which   
                                   //   has already been seen   
                                   //   so is single or is the     
                                   //   same as what a points to     
                          ++       // bump up the beginning one   
            :0;                    // or do nothing    
}                                  //     
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 56 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 7 bytes
```
Þzµ≈;∩fİ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiw556wrXiiYg74oipZsSwIiwiIiwiWzEsMSwyLDMsM10iXQ==)
Jelly porting ftw
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 60 bytes [by tsh](https://codegolf.stackexchange.com/a/250292/76323)
```
a=>(p=a.filter(y=c=>!(y[c]^=1))).concat(a.filter(c=>y[c]),p)
```
[Try it online!](https://tio.run/##PU5LboMwEN33FO6Kseo6IUBCFJllL9AlopHljCMqC4ghkTg9HQxFsuz3mzf@1S/dG193w2fT3nCyatKqgE5paWs3oIdRGVW8w1ia6kfFnHNp2sboAbYE@bPLRceni8fHs/YIke0jLj3q21ft8HtsDOxF9BxsHuTOaYOwkx@7u7iqgir71qF07R0s4Es7uNIqPpVx9Vbmgp3oiQWjcyB0JkGwlNBBMCIJOXtiKYkzXOk6EPxkCVNVJtiRbuJZMI8hdSZ@CigOJVk4OanJf0u@LlrkrXztD1Pp9olFWuw5Wv0B "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 61 bytes
```
x=>x.map(r=t=>r[t]=[r[t]?~++r[t][0]:4,t]).sort().map(t=>t[1])
```
[Try it online!](https://tio.run/##PU7NjoMgEL7vU3ATIku1amvbYG/7AnskpCEWGzdULNKmveyruyO6JRNmvp/54Ec91FC7tvefnT3rseHjk1dPdlU9dtzzygkvuZju428cT10kcp9TLwkbrPOYBC84vUglGQ9O3@6t0zhqhogwp9X5qzX6@9XVOKHR3TdloHujao1XLF5d6IlXte0GazQz9oIbrB/K4BOBM0Lohygp2kJLKYJaw7QDgqIcpjVFADJQEkA5kNO4wGUh6NlshqiCog3cgIsgboJrB3gbpjSEFKFKYLP/lHJ5aKbf4Ut@2Mrfn5ipWZ6s8g8 "JavaScript (Node.js) – Try It Online")
]