Implement the Thanos sorting algorithm

92

15

The sorting algorithm goes like this:

While the list is not sorted, snap half of all items (remove them from the list). Continue until the list is sorted or only one item remains (which is sorted by default). This sorting algorithm may give different results based on implementation.

The item removal procedure is up to the implementation to decide, but the list should be half as long as before after one pass of the item removal procedure. Your algorithm may decide to remove either the first half or the list, the last half of the list, all odd items, all even items, one at a time until the list is half as long, or any not mentioned.

The input list can contain an arbitrary amount of items (within reason, let’s say up to 1000 items), not only perfectly divisible lists of 2^n items. You will have to either remove (n+1)/2 or (n-1)/2 items if the list is odd, either hardcoded or decided randomly during runtime. Decide for yourself: what would Thanos do if the universe contained an odd amount of living things?

The list is sorted if no item is smaller than any previous item. Duplicates may occur in the input, and may occur in the output.

Your program should take in an array of integers (via stdin or as parameters, either individual items or an array parameter), and return the sorted array (or print it to stdout).

Examples:

// A sorted list remains sorted
[1, 2, 3, 4, 5] -> [1, 2, 3, 4, 5]

// A list with duplicates may keep duplicates in the result
[1, 2, 3, 4, 3] -> [1, 3, 3] // Removing every second item
[1, 2, 3, 4, 3] -> [3, 4, 3] -> [4, 3] -> [3] // Removing the first half
[1, 2, 3, 4, 3] -> [1, 2] // Removing the last half

[1, 2, 4, 3, 5] could give different results:

// Removing every second item:
[1, 2, 4, 3, 5] -> [1, 4, 5]

or:

// Removing the first half of the list
[1, 2, 4, 3, 5] -> [3, 5] // With (n+1)/2 items removed
[1, 2, 4, 3, 5] -> [4, 3, 5] -> [3, 5] // With (n-1)/2 items removed

or:

// Removing the last half of the list
[1, 2, 4, 3, 5] -> [1, 2] // With (n+1)/2 items removed
[1, 2, 4, 3, 5] -> [1, 2, 4] // With (n-1)/2 items removed

or:

// Taking random items away until half (in this case (n-1)/2) of the items remain
[1, 2, 4, 3, 5] -> [1, 4, 3] -> [4, 3] -> [4]

vrwim

Posted 2019-03-26T10:21:32.870

Reputation: 2 223

Having a test case which actually requires multiple snaps for multiple different snapping algorithms would be very helpful. – Unrelated String – 2019-03-26T11:01:01.987

23Don't we need to sort and eliminate half of the answers... – Sumner18 – 2019-03-26T14:32:07.463

4Suggested test case: [9, 1, 1, 1, 1]. My own algorithm failed on this input – Conor O'Brien – 2019-03-26T21:03:13.640

Answers

19

Python 3, 38 42 39 bytes

q=lambda t:t>sorted(t)and q(t[::2])or t

Try it online!

-3 bytes thanks to @JoKing and @Quuxplusone

Sara J

Posted 2019-03-26T10:21:32.870

Reputation: 2 576

240 bytes – Jo King – 2019-03-26T12:16:53.277

39 bytes thanks to TFeld's observation that any permutation != sorted(t) must be > sorted(t). – Quuxplusone – 2019-03-26T15:47:04.377

19

R, 41 bytes

x=scan();while(any(x-sort(x)))x=x[!0:1];x

Try it online!

Kirill L.

Posted 2019-03-26T10:21:32.870

Reputation: 6 693

3is.unsorted rather than any(...) would also be 41 bytes. – Giuseppe – 2019-03-26T13:14:56.713

This base method is 44 bytes as a recursive function, might be golfable: Try it online!

– CriminallyVulgar – 2019-03-26T13:57:24.560

13

Python 2, 39 bytes

f=lambda l:l>sorted(l)and f(l[::2])or l

Try it online!

TFeld

Posted 2019-03-26T10:21:32.870

Reputation: 19 246

12

Brachylog (v2), 6 bytes

≤₁|ḍt↰

Try it online!

This is a function submission. Input from the left, output to the right, as usual. (The TIO link uses a command-line argument that automatically wraps the function into a full program, so that you can see it in action.)

Explanation

≤₁|ḍt↰
≤₁       Assert that {the input} is sorted {and output it}
  |      Handler for exceptions (e.g. assertion failures):
   ḍ     Split the list into two halves (as evenly as possible)
    t    Take the last (i.e. second) half
     ↰   Recurse {and output the result of the recursion}

Bonus round

≤₁|⊇ᵇlᵍḍhtṛ↰

Try it online!

The snap's meant to be random, isn't it? Here's a version of the program that choses the surviving elements randomly (while ensuring that half survive at each round).

≤₁|⊇ᵇlᵍḍhtṛ↰
≤₁            Assert that {the input} is sorted {and output it}
  |           Handler for exceptions (e.g. assertion failures):
   ⊇ᵇ         Find all subsets of the input (preserving order)
     lᵍ       Group them by length
       ḍht    Find the group with median length:
         t      last element of
        h       first
       ḍ        half (split so that the first half is larger)
          ṛ   Pick a random subset from that group
           ↰  Recurse

This would be rather shorter if we could reorder the elements, but whyever would a sorting algorithm want to do that?

ais523

Posted 2019-03-26T10:21:32.870

Reputation: 11

13One byte per infinity stone. – djechlin – 2019-03-26T20:42:41.237

1@djechlin the infinity byte is why you must go for the head and especially the jaw. – user64742 – 2019-03-28T00:44:38.410

10

Perl 6, 30 bytes

$!={[<=]($_)??$_!!.[^*/2].&$!}

Try it online!

Recursive function that removes the second half of the list until the list is sorted.

Explanation:

$!={                         }    # Assign the function to $!
    [<=]($_)??                    # If the input is sorted
              $_                  # Return the input
                !!                # Else
                  .[^*/2]         # Take the first half of the list (rounding up)
                         .&$!     # And apply the function again

Jo King

Posted 2019-03-26T10:21:32.870

Reputation: 38 234

9

C# (Visual C# Interactive Compiler), 76 bytes

g=>{while(!g.OrderBy(x=>x).SequenceEqual(g))g=g.Take(g.Count()/2);return g;}

Try it online!

Expired Data

Posted 2019-03-26T10:21:32.870

Reputation: 3 129

8

Wolfram Language (Mathematica), 30 bytes

#//.x_/;Sort@x!=x:>x[[;;;;2]]&

Try it online!

@Doorknob saved 12 bytes

J42161217

Posted 2019-03-26T10:21:32.870

Reputation: 15 931

1Instead of taking the first half, you could save some bytes by taking every other element (x[[;;;;2]]). – Doorknob – 2019-03-28T03:40:22.353

@Doorknob yes of course... – J42161217 – 2019-03-28T10:24:00.807

thought there could be some savings by using OrderedQ, but couldn't make it work – Greg Martin – 2019-03-29T07:15:08.607

@GregMartin I used OrderedQ in my very first approach (see edits) – J42161217 – 2019-03-29T09:19:44.817

8

Java 10, 106 97 bytes

L->{for(;;L=L.subList(0,L.size()/2)){int p=1<<31,f=1;for(int i:L)f=p>(p=i)?0:f;if(f>0)return L;}}

-9 bytes thanks to @OlivierGrégoire.

Try it online.

Only leave the first halve of the list every iteration, and removes \$\frac{n+1}{2}\$ items if the list-size is odd.

Explanation:

L->{               // Method with Integer-list as both parameter and return-type
  for(;;           //  Loop indefinitely:
      L=L.subList(0,L.size()/2)){
                   //    After every iteration: only leave halve the numbers in the list
    int p=1<<31,   //   Previous integer, starting at -2147483648
        f=1;       //   Flag-integer, starting at 1
    for(int i:L)   //   Inner loop over the integer in the list:
      f=p>(p=i)?   //    If `a>b` in a pair of integers `a,b`:
         0         //     Set the flag to 0
        :          //    Else (`a<=b`):
         f;        //     Leave the flag the same
    if(f>0)        //   If the flag is still 1 after the loop:
      return L;}}  //    Return the list as result

Kevin Cruijssen

Posted 2019-03-26T10:21:32.870

Reputation: 67 575

n->{for(;n.reduce((1<<31)+0d,(a,b)->a==.5|b<a?.5:b)==.5;n=n.skip(n.count()/2));return n;} is shorter using streams, but I haven't been able to figure out how to avoid the java.lang.IllegalStateException: stream has already been operated upon or closed error after returning the stream – Embodiment of Ignorance – 2019-03-26T21:09:22.263

@EmbodimentofIgnorance this happens because reduce is a terminal operation that closes the stream. You won't ever be able to call reduce twice on the same stream. You can create a new stream, though. – Olivier Grégoire – 2019-03-27T15:37:35.953

197 bytes – Olivier Grégoire – 2019-03-27T16:05:20.950

@OlivierGrégoire That order looks so simple now that I see it.. Sometimes it takes a look from another angle to see the obvious others initially miss I guess. :) Thanks! – Kevin Cruijssen – 2019-03-27T18:17:22.940

1No worries, it wasn't obvious: I worked to get there. I tested at least 10 versions before finding that one ;) – Olivier Grégoire – 2019-03-28T13:02:02.087

7

JavaScript (ES6),  49  48 bytes

Saved 1 byte thanks to @tsh

Removes every 2nd element.

f=a=>a.some(p=c=>p>(p=c))?f(a.filter(_=>a^=1)):a

Try it online!

Arnauld

Posted 2019-03-26T10:21:32.870

Reputation: 111 334

p++&1 -> a^=1 – tsh – 2019-03-29T08:11:24.013

6

05AB1E, 8 7 bytes

[Ð{Q#ιн

-1 byte thanks to @Emigna.

Removes all odd 0-indexed items every iteration, so removes \$\frac{n-1}{2}\$ items if the list-size is odd.

Try it online or verify some more test cases (or verify those test cases with step-by-step for each iteration).

7 bytes alternative by @Grimy:

ΔÐ{Ê>äн

Removes the last \$\frac{n}{2}\$ items (or \$\frac{n-1}{2}\$ items if the list-size is odd) every iteration.

Try it online or verify some more test cases (or verify those test cases with step-by-step for each iteration).

Explanation:

[        # Start an infinite loop:
 Ð       #  Triplicate the list (which is the implicit input-list in the first iteration)
  {Q     #  Sort a copy, and check if they are equal
    #    #   If it is: Stop the infinite loop (and output the result implicitly)
  ι      #  Uninterweave: halve the list into two parts; first containing all even-indexed
         #  items, second containing all odd-indexed items (0-indexed)
         #   i.e. [4,5,2,8,1] → [[4,2,1],[5,8]]
   н     #  And only leave the first part

Δ        # Loop until the result no longer changes:
 Ð       #  Triplicate the list (which is the implicit input-list in the first iteration)
  {Ê     #  Sort a copy, and check if they are NOT equal (1 if truthy; 0 if falsey)
    >    #  Increase this by 1 (so 1 if the list is sorted; 2 if it isn't sorted)
     ä   #  Split the list in that many parts
      н  #  And only leave the first part
         # (and output the result implicitly after it no longer changes)

Kevin Cruijssen

Posted 2019-03-26T10:21:32.870

Reputation: 67 575

3You can use ι instead of if you switch to a keep every other element strategy. – Emigna – 2019-03-26T12:07:11.160

1Alternative 7 using the "remove the last half" strategy: ΔÐ{Ê>äн – Grimmy – 2019-03-29T10:03:19.410

@Grimy That's a pretty nice approach as well. Shall I add it to my post (crediting you of course), or do you want to post it as a separated answer? – Kevin Cruijssen – 2019-03-29T10:07:15.917

Feel free to add it. – Grimmy – 2019-03-29T10:07:45.147

6

TI-BASIC (TI-84), 47 42 45 44 bytes

-1 byte thanks to @SolomonUcko!

Ans→L1:Ans→L2:SortA(L1:While max(L1≠Ans:iPart(.5dim(Ans→dim(L2:L2→L1:SortA(L1:End:Ans

Input list is in Ans.
Output is in Ans and is implicitly printed out.

Explanation:

Ans→L1                  ;store the input into two lists
Ans→L2
SortA(L1                ;sort the first list
                        ; two lists are needed because "SortA(" edits the list it sorts
While max(L1≠Ans        ;loop until both lists are strictly equal
iPart(.5dim(Ans→dim(L2  ;remove the latter half of the second list
                        ; removes (n+1)/2 elements if list has an odd length
L2→L1                   ;store the new list into the first list (updates "Ans")
SortA(L1                ;sort the first list
End
Ans                     ;implicitly output the list when the loop ends

Note: TI-BASIC is a tokenized language. Character count does not equal byte count.

Tau

Posted 2019-03-26T10:21:32.870

Reputation: 1 935

I think you can replace not(min(L1=Ans with max(L1≠Ans to save a byte. – Solomon Ucko – 2019-04-01T11:22:44.983

6

Ruby, 37 bytes

->r{r=r[0,r.size/2]while r.sort!=r;r}

Try it online!

G B

Posted 2019-03-26T10:21:32.870

Reputation: 11 099

36 bytes recursively – Kirill L. – 2019-03-26T20:41:50.317

4

Jelly, 7 bytes

m2$⁻Ṣ$¿

Try it online!

Erik the Outgolfer

Posted 2019-03-26T10:21:32.870

Reputation: 38 134

3

Octave, 49 bytes

l=input('');while(~issorted(l))l=l(1:2:end);end;l

Try it online! This was a journey where more boring is better. Note the two much more interesting entries below:

50 bytes

function l=q(l)if(~issorted(l))l=q(l(1:2:end));end

Try it online! Instead of the uninteresting imperative solution, we can do a recursive solution, for only one additional byte.

53 bytes

f(f=@(g)@(l){l,@()g(g)(l(1:2:end))}{2-issorted(l)}())

Try it online! Yep. A recursive anonymous function, thanks to @ceilingcat's brilliant answer on my question. An anonymous function that returns a recursive anonymous function by defining itself in its argument list. I like anonymous functions. Mmmmm.

Sanchises

Posted 2019-03-26T10:21:32.870

Reputation: 8 530

3

Haskell, 57 55 bytes (thanks to ASCII-only)

f x|or$zipWith(>)x$tail x=f$take(div(length x)2)x|1>0=x

Try it online!


Original Code:

f x|or$zipWith(>)x(tail x)=f(take(div(length x)2)x)|1>0=x

Try it online!


Ungolfed:

f xs | sorted xs = f (halve xs)
     | otherwise = xs

sorted xs = or (zipWith (>) xs (tail xs))

halve xs = take (length xs `div` 2) xs

Sachera

Posted 2019-03-26T10:21:32.870

Reputation: 51

1Welcome to PPCG! – Rɪᴋᴇʀ – 2019-03-28T05:20:35.843

56 – ASCII-only – 2019-03-28T05:38:03.253

57 :( – ASCII-only – 2019-03-28T05:44:55.460

55 – ASCII-only – 2019-03-28T05:55:18.853

2

MATL, 11 bytes

tv`1L)ttS-a

Try it online!

This works by removing every second item.

Explanation

t      % Take a row vector as input (implicit). Duplicate
v      % Vertically concatenate the two copies of the row vector. When read with
       % linear indexing (down, then across), this effectively repeats each entry
`      % Do...while
  1L)  %   Keep only odd-indexed entries (1-based, linear indexing)
  t    %   Duplicate. This will leave a copy for the next iteration
  tS   %   Duplicate, sort
  -a   %   True if the two arrays differ in any entry
       % End (implicit). A new iteration starts if the top of the stack is true
       % Display (implicit). Prints the array that is left on the stack

Luis Mendo

Posted 2019-03-26T10:21:32.870

Reputation: 87 464

2Broken for initially sorted list: [1, 2, 3, 4, 5] should remain [1, 2, 3, 4, 5] – Falco – 2019-03-26T13:06:16.903

@Falco Thanks! Corrected now – Luis Mendo – 2019-03-26T14:19:02.200

2

Japt, 10 bytes

eUñ)?U:ßUë

Try it

eUñ)?U:ßUë     :Implicit input of array U
e              :Compare equality with
 Uñ            :  U sorted
   )           :End compare
    ?U:        :If true then return U else
       ß       :Run the programme again with input
        Uë     :  Every second element of U

Shaggy

Posted 2019-03-26T10:21:32.870

Reputation: 24 623

2

Gaia, 9 8 bytes

eo₌⟨2%⟩↻

Try it online!

Explanation:

e		| eval input as a list
       ↻	| until
 o		| the list is sorted
  ₌		| push additional copy
   ⟨2%⟩  	| and take every 2nd element

Giuseppe

Posted 2019-03-26T10:21:32.870

Reputation: 21 077

2

Java (JDK), 102 bytes

n->{for(;n.stream().reduce((1<<31)+0d,(a,b)->a==.5|b<a?.5:b)==.5;n=n.subList(0,n.size()/2));return n;}

There's already a C# answer, so I decided to try my hand on a Java answer.

Try it online!

Embodiment of Ignorance

Posted 2019-03-26T10:21:32.870

Reputation: 7 014

Time to try F# :)

– aloisdg moving to codidact.com – 2019-03-28T14:35:38.100

2

Husk, 6 5 bytes

1 byte saved thanks to Zgarb

ΩΛ<Ċ2

Try it online!

Explanation

ΩΛ<Ċ2
Ω         Repeat until
 Λ<         all adjacent pairs are sorted (which means the list is sorted)
   Ċ2         drop every second element from the list

Leo

Posted 2019-03-26T10:21:32.870

Reputation: 8 482

This is 11 bytes, not 6.

› echo -n "ΩΛ<(←½" | wc --bytes 11 – Mike Holler – 2019-03-27T20:11:51.947

@MikeHoller https://github.com/barbuz/Husk/wiki/Codepage

– Xan – 2019-03-27T22:51:47.447

@MikeHoller As many other golfing languages, Husk uses a custom code page, in order to have access to more different characters: https://github.com/barbuz/Husk/wiki/Codepage

– Leo – 2019-03-27T22:53:02.037

Thank you, I learned something today :) – Mike Holler – 2019-03-28T13:30:20.530

1Use Ċ2 instead of (←½ to save a byte. – Zgarb – 2019-04-21T07:58:24.047

2

Crystal, 58 bytes

With Array#sort (58 bytes):

->(a : Array(Int32)){while a!=a.sort;a.pop a.size/2;end;a}

Try it online!

Without Array#sort (101 bytes):

->(a : Array(Int32)){while a.map_with_index{|e,i|e>a.fetch i+1,Int32::MAX}.any?;a.pop a.size/2;end;a}

Try it online!

Kinxer

Posted 2019-03-26T10:21:32.870

Reputation: 31

2

C++ (gcc), 103 bytes

I can't comment, but I improved the version from movatica by reducing the includes, and using auto.

-2 Bytes: ceilingcat
-2 Bytes: ASCII-only

#include<regex>
auto f(auto l){while(!std::is_sorted(l.begin(),l.end()))l.resize(l.size()/2);return l;}

Try it online!

peterzuger

Posted 2019-03-26T10:21:32.870

Reputation: 73

1any reason you can't just use l.size()/2? – ASCII-only – 2019-05-03T10:12:49.060

Yes, it does not work that way :) – peterzuger – 2019-05-06T10:39:31.940

1what do you mean? returning a list of size (n+1)/2 or (n-1)/2 are both valid. hmm.... – ASCII-only – 2019-05-06T14:02:15.503

Ohh oops did'nt see that thanks – peterzuger – 2019-05-07T06:07:48.527

2

Julia 1.0, 30 bytes

-x=x>sort(x) ? -x[1:2:end] : x

Try it online!

Takes every second element of the array if not sorted.

niczky12

Posted 2019-03-26T10:21:32.870

Reputation: 301

use an ASCII operator like - for 20 bytes. also we almost always don't count chars :| so it'd be nice if that was removed from the header – ASCII-only – 2019-05-03T10:11:39.373

Changed that. Thanks for 2 bytes! – niczky12 – 2019-05-03T12:27:25.617

1

VDM-SL, 99 bytes

f(i)==if forall x in set inds i&x=1or i(x-1)<=i(x) then i else f([i(y)|y in set inds i&y mod 2=0]) 

Never submitted in vdm before, so not certain on language specific rules. So I've submitted as a function definition which takes a seq of int and returns a seq of int

A full program to run might look like this:

functions
f:seq of int +>seq of int
f(i)==if forall x in set inds i&x=1or i(x-1)<=i(x) then i else f([i(y)|y in set inds i&y mod 2=0]) 

Expired Data

Posted 2019-03-26T10:21:32.870

Reputation: 3 129

1

Pyth, 10 bytes

.W!SIHhc2Z

Try it online here. This removes the second half on each iteration, rounding down. To change it to remove the first half, rounding up, change the h to e.

.W!SIHhc2ZQ   Q=eval(input())
              Trailing Q inferred
  !SIH        Condition function - input variable is H
   SIH          Is H invariant under sorting?
  !             Logical not
      hc2Z    Iteration function - input variable is Z
       c2Z      Split Z into 2 halves, breaking ties to the left
      h         Take the first half
.W        Q   With initial value Q, execute iteration function while condition function is true

Sok

Posted 2019-03-26T10:21:32.870

Reputation: 5 592

Taking every other element of the list is shorter. Replace hc with %. This also lets you delete the trailing lambda variable Z and let Pyth fill it implicitly, for a total 2 bytes saved. – hakr14 – 2019-06-09T03:37:58.197

1

C++ (gcc), 139 137 116 bytes

-2 bytes thanx to ceilingcat, -21 bytes thanx to PeterZuger

#include<regex>
auto f(std::vector<int>l){while(!std::is_sorted(l.begin(),l.end()))l.resize(-~l.size()/2);return l;}

Resize the vector to its first half until it's sorted.

Try it online!

movatica

Posted 2019-03-26T10:21:32.870

Reputation: 635

1Imports are rquired to be included in the byte count, so you have to add the includes – Embodiment of Ignorance – 2019-04-25T21:18:28.123

Thanx, i'll add them. – movatica – 2019-04-25T21:27:02.860

1

K (oK), 22 20 bytes

Solution:

{(*2 0N#x;x)x~x@<x}/

Try it online!

Iterate over the input until it's sorted... if it's not sorted take first n/2 items.

{(*2 0N#x;x)x~x@<x}/ / the solution
{                 }/ / lambda that iterates
                <x   / indices that sort x ascending (<)
              x@     / apply (@) these indices back to x
            x~       / matches (~) x? returns 0 or 1
 (       ; )         / 2-item list which we index into
          x          / original input (ie if list was sorted)
       #x            / reshape (#) x
   2 0N              / as 2 rows
  *                  / take the first one      

Edits:

  • -2 bytes thanks to ngn

streetster

Posted 2019-03-26T10:21:32.870

Reputation: 3 635

1(.5*#x)#x -> *2 0N#x – ngn – 2019-06-07T23:07:23.637

I considered doing 2 0N but assumed it would be longer (without testing), thanks! – streetster – 2019-06-09T17:56:27.743

1

Julia 1.0, 33 bytes

-a=issorted(a) ? a : -a[1:end÷2]

Try it online!

gggg

Posted 2019-03-26T10:21:32.870

Reputation: 1 715

0

Retina, 38 bytes

\d+
*
/(_+),(?!\1)/+`,_+(,?)
$1
_+
$.&

Try it online! Takes comma-separated numbers. Explanation:

\d+
*

Convert to unary.

/(_+),(?!\1)/+`

Repeat while the list is unsorted...

,_+(,?)
$1

... delete every even element.

_+
$.&

Convert to decimal.

Neil

Posted 2019-03-26T10:21:32.870

Reputation: 95 035

0

C (gcc), 66 bytes

Snaps off the second half of the list each iteration (n/2+1 elements if the length is odd).

Try it online!

Takes input as a pointer to the start of an array of int followed by its length. Outputs by returning the new length of the array (sorts in-place).

t(a,n,i)int*a;{l:for(i=0;i<n-1;)if(a[i]>a[++i]){n/=2;goto l;}a=n;}

Ungolfed version:

t(a, n, i) int *a; { // take input as a pointer to an array of int, followed by its length; declare a loop variable i
  l: // jump label, will be goto'ed after each snap
  for(i = 0; i < n - 1; ) { // go through the whole array …
    if(a[i] > a[++i]) { // … if two elements are in the wrong order …
      n /= 2; // … snap off the second half …
      goto l; // … and start over
    }
  }
  a = n; // implicitly return the new length
}

O.O.Balance

Posted 2019-03-26T10:21:32.870

Reputation: 1 499

Suggest ~i+n instead of i<n-1 – ceilingcat – 2019-04-12T17:19:23.360

0

Clojure, 65 bytes

(defn t[l](if(apply <= l)l(recur(take(/(count l)2)(shuffle l)))))

Try it online!

Ethan McCue

Posted 2019-03-26T10:21:32.870

Reputation: 131

45? – ASCII-only – 2019-03-28T06:36:08.527

43? 42? – ASCII-only – 2019-03-28T06:42:16.593

0

MATLAB, 57 bytes

Callable as f(a), where a=[1,2,3,4,5]

f=@(x)eval('while~isequal(sort(x),x);x=x(1:end/2);end;x')

Example of usage:

>> a = [1, 2, 4, 3, 5];
>> f(a)

a =
     1     2

aaaaa says reinstate Monica

Posted 2019-03-26T10:21:32.870

Reputation: 381

0

Zsh, 51 bytes

56 (+5) to call the function, 47 (-4) if not a function, but saved as an executable with a proper #! header (replace the recursive f call with $0).

f(){[ "$*" = "${${(n)@}[*]}" ]&&<<<$@||f $@[0,#/2]}

Try it online!

There is no "is-sorted" builtin in zsh, but there are some "sort-array" builtins. We use the parameter expansion flag n, but o or i would also work. We then have to use [*] and quote to induce joining. This is shorter than alternatives (like zipping them together and comparing pairwise).

GammaFunction

Posted 2019-03-26T10:21:32.870

Reputation: 2 838

0

TI-Basic (TI-84), 29 30 36 bytes

Ans->L₁
While 1<dim(L₁
If 0≤min(ΔList(L₁:Then
L₁
Return:End
iPart(.5dim(L₁->dim(L₁
End

Input and output are through Ans.

Solomon Ucko

Posted 2019-03-26T10:21:32.870

Reputation: 439

L1 is not legal input; you need to either use Ans or write Input L1. Same for output, either Ans or display. – lirtosiast – 2019-06-06T06:50:27.970

0

C++ 17 , 589 bytes

I used recursion to solve it. Submitted this solution in codeforces and got accepted. Btw, I still can't stop laughing! I mean seriously, Thanos sort!

#include <bits/stdc++.h> 
using namespace std;int n, *a; int f(int start123, int end123){int start, end;start = start123; end = end123;if(start == end){    return 1; }int ret=0, temp=0;bool flag  = true;for(int i=start; i<end; i++){ if(a[i]<=a[i+1]){   ret++; }else{    flag=false; break; } }int mid = (start+end)>>1; if(flag){    ret=ret+1; }else{ int a,b; a =  f(start, mid);b = f(mid+1, end);ret = max( a, b );}return ret;}int main(int argc, char const *argv[]){    cin>>n;a = new int[n+10];for(int i=1; i<=n; i++){cin>>a[i];}int ans = f(1,n);cout<<ans<<"\n";if(!a)delete[] a;return 0;}

Qazi Fahim Farhan

Posted 2019-03-26T10:21:32.870

Reputation: 101

2

Hi and welcome to PPCG, the criterion of this question is code-golf, that means we are trying to solve the problem in as few bytes as possible. Typically people will post the number of bytes for their answer along with the answer (so for yours: 1120 bytes), your aim should be to reduce this! May I recommend starting by removing all unneccesary whitespace, naming your variables with single characters and looking at tips for golfing in c++

– Expired Data – 2019-04-02T14:35:28.037

Thank you Expired Data. I'll try to do better next time – Qazi Fahim Farhan – 2019-04-03T06:26:50.993

0

F# (.NET Core), 67 61 bytes

let rec t l=if l=(List.sort l)then l else t l.[0..l.Length/2]

Try it online!

LSM07

Posted 2019-03-26T10:21:32.870

Reputation: 191

0

Perl 6, 32 bytes

{($_,*[^*/2]...{[<=] @$_})[*-1]}

-2 bytes thanks to Jo King

Try it online!

bb94

Posted 2019-03-26T10:21:32.870

Reputation: 1 831

0

Perl 5 -a, 50 bytes

@b=sort{$a-$b}@F while"@b"ne"@F"&&($#F/=2);say"@F"

Try it online!

Xcali

Posted 2019-03-26T10:21:32.870

Reputation: 7 671

0

Rust (2018 edition), 79 78 bytes

|v:&mut Vec<_>|while{let q=&mut v.clone();q.sort();q<v}{v.resize(v.len()/2,0)}

Try it online!

This will be golfable if slice::is_sorted gets stabilized, but right now the required feature flag offsets all gains.

NieDzejkob

Posted 2019-03-26T10:21:32.870

Reputation: 4 630

feature flags are free though :P - they just count as a separate language – ASCII-only – 2019-05-06T14:02:48.997

@ASCII-only for Rust, feature flags are not commandline arguments, but special syntax in the code itself. – NieDzejkob – 2019-05-06T19:36:47.850

Huh, no commandline option (like C# and Haskell) huh – ASCII-only – 2019-05-07T01:09:54.957

0

PHP, 86 bytes

function t($a){for(;$n=$a[+$i++];$l=$n)$f|=$n<$l;return$f?t(array_slice($a,$i/2)):$a;}

Try it online!

Night2

Posted 2019-03-26T10:21:32.870

Reputation: 5 484

0

Python 2, 52 bytes

a=input()
while a!=sorted(a):a=a[:len(a)//2]
print a

nice!

Sagittarius

Posted 2019-03-26T10:21:32.870

Reputation: 169