1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-197/#TASK2
 3 #
 4 # You are given a list of integers, @list.
 5 #
 6 # Write a script to perform Wiggle Sort on the given list.
 7 #
 8 # # Wiggle sort would be such as list[0] < list[1] > list[2] < list[3]...
 9 
10 use strict;
11 use warnings;
12 
13 # sample input values
14 my $inputs = [
15    [1,5,1,1,6,4],
16    [1,3,2,2,3,1],
17    [1,2,3,4,5],
18    [1,1,1,2,2,2,3,3,4,4],
19 ];
20 
21 # handle all input arrays from sample list above
22 foreach my $input (@$inputs) {
23    print "(" . join(", ", @$input) . ") returns (" . join(", ", wiggle_sort(@$input)) . ")\n";
24 }
25 
26 # wiggle sort has to jump up and down every time
27 sub wiggle_sort {
28    # let's start by sorting all values
29    my @values = sort {$a <=> $b} @_;
30    my @result = ();
31    # by starting in the middle of the sorted array and walking down while at
32    # the same time starting at the top and wakling down as well, we can always
33    # make sure we have a bigger and a smaller value next to each other
34    my $start = int($#values/2);
35    my ($i, $j) = ($start, $#values);
36    while($i >= 0 && $j > $start) {
37       push @result, $values[$i--], $values[$j--];
38    }
39    # if we have an odd number of values in the original array, we now have
40    # one more value to take care of; in this case $i just reached 0 by means of
41    # the last "$i--" in the loop
42    push @result, $values[$i] if $i == 0;
43    return @result;
44 }