Arrays and arrays
Weekly challenge 310 — 24 February 2025
Week 310: 24 Feb 2025
You are given an array of integers. Write a script to sort odd index elements in decreasing order and even index elements in increasing order in the given array.
Example 1 Input: @ints = (4, 1, 2, 3) Output: (2, 3, 4, 1) Even index elements: 4, 2 => 2, 4 (increasing order) Odd index elements : 1, 3 => 3, 1 (decreasing order) Example 2 Input: @ints = (3, 1) Output: (3, 1) Example 3 Input: @ints = (5, 3, 2, 1, 4) Output: (2, 3, 4, 1, 5) Even index elements: 5, 2, 4 => 2, 4, 5 (increasing order) Odd index elements : 3, 1 => 3, 1 (decreasing order)
Three steps are needed:
But when would you ever need to do that?
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2025-02-24 use utf8; # Week 310 - task 2 - Sort odd even use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; sort_odd_even(4, 1, 2, 3); sort_odd_even(3, 1); sort_odd_even(5, 3, 2, 1, 4); sort_odd_even(3, 7, 9, 3, 2, 6, 8, 1, 0, 4, 2, 5); sort_odd_even(-3, -2, -1, 0, 1, 2, 3); sub sort_odd_even { my (@array, $v, @odds, @evens, @output); # separate odds and evens @array = @_; for $v (0 .. $#array) { unshift @odds, $array[$v] if $v & 1; unshift @evens, $array[$v] unless $v & 1; } # sort them as specified @odds = sort {$b <=> $a} @odds; @evens = sort {$a <=> $b} @evens; # recreate @array in sorted order for $v (0 .. $#array) { push @output, shift @odds if $v & 1; push @output, shift @evens unless $v & 1; } say qq[\nInput: \@array = (] . join(', ', @array) . ')'; say qq[Output: = (] . join(', ', @output) . ')'; }
Input: @array = (4, 1, 2, 3) Output: = (2, 3, 4, 1) Input: @array = (3, 1) Output: = (3, 1) Input: @array = (5, 3, 2, 1, 4) Output: = (2, 3, 4, 1, 5) Input: @array = (3, 7, 9, 3, 2, 6, 8, 1, 0, 4, 2, 5) Output: = (0, 7, 2, 6, 2, 5, 3, 4, 8, 3, 9, 1) Input: @array = (-3, -2, -1, 0, 1, 2, 3) Output: = (-3, 2, -1, 0, 1, -2, 3)
Any content of this website which has been created by Peter Campbell Smith is in the public domain