PWC213 - Fun Sort


Here we are with TASK #1 from The Weekly Challenge #213. Enjoy!

The challenge

You are given a list of positive integers.

Write a script to sort the all even integers first then all odds in ascending order.

Example 1

Input: @list = (1,2,3,4,5,6)
Output: (2,4,6,1,3,5)

Example 2

Input: @list = (1,2)
Output: (2,1)

Example 3

Input: @list = (1)
Output: (1)

The questions

I guess the output should be a single list with the described order, so it will be what I’ll assume.

The solution

For the Raku solution, I opted for splitting the input list first, then sorting the two lists separately:

#!/usr/bin/env raku
use v6;
sub MAIN (*@args) { say fun-sort(@args ?? @args !! [1 .. 6]) }

sub fun-sort (@input) {
   my (@even, @odd);
   for @input -> $v {
      if $v %% 2 { @even.push: $v.Int }
      else       { @odd.push: $v.Int  }
   return (@even.sort, @odd.sort).flat;

In the Perl variant, though, I decided to sort first, then sweep through the array from begin to end, moving odd elements to the end. At each iteration, either we move one position ahead, or we move the last position to consider one step behind, so we will anyway only consider each element once. This approach preserves the ordering or odd items, so we’re done.

#!/usr/bin/env perl
use v5.24;
use warnings;
use experimental 'signatures';

say '(', join(',', fun_sort(@ARGV ? @ARGV : (1 .. 6))), ')';

sub fun_sort (@input) {
   @input = sort { $a <=> $b } @input;
   my $start = 0;
   my $stop = $#input;
   while ($start <= $stop) {
      if ($input[$start] % 2) { # move odds at the end
         push @input, splice @input, $start, 1;
      else {
   return @input;

Stay safe and have fun… sorting!

Comments? Octodon, , GitHub, Reddit, or drop me a line!