Peter’s blog ✴ Week 391 ✴ 14 September 2026
THE WEEKLY CHALLENGE
Medians and stacks
You are given two sorted arrays. Write a script to merge the two given sorted arrays and return the median of the merged array.
Example 1 Input: @arr1 = (2), @arr2 = (4) Output: 3.0 Merged array: (2,4) Median: (2+4)/2 => 3 Example 2 Input: @arr1 = (1,2,3), @arr2 = (7,8,9,10) Output: 7.0 Merged array: (1,2,3,7,8,9,10) Length of merged array is 7, the 4th element is 7. Example 3 Input: @arr1 = (), @arr2 = (10,20,30,40) Output: 25.0 Merged array: (10,20,30,40) Median: (20+30)/2 => 25 Example 4 Input: @arr1 = (100), @arr2 = (1,2,3,4,5,6,7) Output: 4.5 Merged array: (1,2,3,4,5,6,7,100) Median: (4+5)/2 => 4.5 Example 5 Input: @arr1 = (1,2,2), @arr2 = (2,2,3) Output: 2.0 Merged array: (1,2,2,2,2,3) Median: (2+2)/2 => 2
No doubt someone will have a one-liner for this, but I prefer the more readable answer. In any case, the easy way to do this is to concatenate the arrays, sort the result and then:
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2026-09-14 use utf8; # Week 391 - task 1 - Array median use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; array_median([2], [4]); array_median([1, 2, 3], [7, 8, 9, 10]); array_median([], [10, 20, 30, 40]); array_median([100], [1, 2, 3, 4, 5, 6, 7]); array_median([1, 2, 2], [2, 2, 3]); sub array_median { my (@merged, $middle, $median); # merge, sort and count arrays push @merged, @{$_[$_]} for 0 .. 1; @merged = sort {$a <=> $b} @merged; $middle = @merged / 2 - 1; # even number of entries if ($middle == int($middle)) { $median = ($merged[$middle] + $merged[$middle + 1]) / 2; # odd number of entries } else { $median = ($merged[$middle + 1]); } # report say qq[\nInput: \@arr1 = (] . join(', ', @{$_[0]}) . '), @arr2 = (' . join(', ', @{$_[1]}) . ')'; say qq[Output: $median]; }
12 lines of code
Input: @arr1 = (2), @arr2 = (4) Output: 3 Input: @arr1 = (1, 2, 3), @arr2 = (7, 8, 9, 10) Output: 7 Input: @arr1 = (), @arr2 = (10, 20, 30, 40) Output: 25 Input: @arr1 = (100), @arr2 = (1, 2, 3, 4, 5, 6, 7) Output: 4.5 Input: @arr1 = (1, 2, 2), @arr2 = (2, 2, 3) Output: 2
Any content of this website which has been created by Peter Campbell Smith is in the public domain