Example/SortedMerge/Array.pm untested

filter: Statementstmt 0.0% 0 / 39 Branchbran 0.0% 0 / 2 Conditioncond 0.0% 0 / 10 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 0.0% 0 / 8 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 71 CC 2 SCAR 10.6
CC
2
Cov
0%
merge
6.0
new
2.0
split_half
2.0
CRAP 2.9
1 ########################################################################
2 # housekeeping
3 ########################################################################
4 package LinkedList::Single::Example::SortedMerge::Array v2.0.0;
5 use v5.40;
6  
7 use Carp qw( croak );
8  
9 ########################################################################
10 # the same interface over arrays. an item is [ $key, @payload ]; the
11 # comparator sees the keys only; a merge is stable.
12 #
13 # the arrays are not consumed: merge and merge_sort return new arrays
14 # and leave their arguments as they were. (the list versions cannot
15 # leave their arguments intact; the tests compare the results only.)
16 ########################################################################
17  
18 sub new( $class, %arg )
19 {
20 my $cmp = $arg{ cmp } // sub( $x, $y ) { $x <=> $y };
21  
22 bless { cmp => $cmp } => $class
23 }
24  
25 ########################################################################
26 # two indexes, one output.
27 ########################################################################
28  
29 sub merge( $self, $x, $y )
30 {
31 my $cmp = $self->{ cmp };
32 my @out = ();
33 my $i = 0;
34 my $j = 0;
35  
36 while( $i < $x->@* && $j < $y->@* )
37 {
38 push @out
39 , $cmp->( $x->[ $i ][ 0 ], $y->[ $j ][ 0 ] ) <= 0
40 ? $x->[ $i++ ]
41 : $y->[ $j++ ]
42 ;
43 }
44  
45 push @out, $x->@[ $i .. $x->$#* ];
46 push @out, $y->@[ $j .. $y->$#* ];
47  
48 \@out
49 }
50  
51 sub split_half( $self, $list )
52 {
53 my $count = $list->@*;
54  
55 $count > 1
56 or croak "Botched split_half: a list of $count nodes has no halves";
57  
58 my $half = int( ( $count + 1 ) / 2 );
59  
60 (
61 [ $list->@[ 0 .. $half - 1 ] ]
62 , [ $list->@[ $half .. $list->$#* ] ]
63 )
64 }
65  
66 sub merge_sort( $self, $list )
67 {
68 $list->@* > 1
69 or return [ $list->@* ];
70  
71 my( $left, $right ) = $self->split_half( $list );
72  
73 $self->merge
74 (
75 $self->merge_sort( $left )
76 , $self->merge_sort( $right )
77 )
78 }
79  
80 ########################################################################
81 # test support
82 ########################################################################
83  
84 sub build( $self, @item )
85 {
86 [ map { [ $_->@* ] } @item ]
87 }
88  
89 sub contents( $self, $list )
90 {
91 [ map { [ $_->@* ] } $list->@* ]
92 }
93  
94 1
95 __END__