In Lab 4 the recursive solutions were not very efficient, and we hypothesized that at least part of the inefficiency was due to the copying of large arrays used as parameters. In this lab we will use references to make these routines more efficient. A reference is a way to refer directly to a location in memory, so that two references to the same array will refer to the same locations. For example:
@a = (1, 2, 3);
$arrayref = \@a; # The backslash creates a reference
$arrayref2 = $arrayref; # arrayref2 also refers to array a
@b = @a; # Array b is a copy of array a, in a different location
$$arrayref[0] = 4; # Changes $a[0] to 4, $b[0] is unchanged
$$arrayref2[1] = 5; # Changes $a[1] to 5, $b[1] is unchanged
$b[2] = 6; # Changes $b[2] to 6, $a[2] is unchanged
Rewrite the three subroutines from Lab 4 using references to minimize the amount of copying of array elements. The first subroutine should just have a single parameter, the reference to the array. To avoid modifying the original array, the second subroutine shouldn't pop elements, but should pass an extra parameter indicating how much of the array has been processed. The initial call should be of the form
$sum = unbal_add( $#numlist, \@numlist );
where the first parameter is the index of the next element to be added. Each recursive call should subtract one from the first parameter and pass the second parameter (the reference) as is.
The third subroutine should also avoid popping elements by passing two extra parameters indicating the range of subscripts to be summed. For example, the call
$sum = bal_add( 4, 7, \@a );
should add $a[4], $a[5], $a[6], and $a[7]. Each recursive call should split the range in half (unless it's just one or two elements) and sum the results of the two recursive calls. For example the above call should result in the recursive calls
bal_add( 4, 5, \@a ) + bal_add( 6, 7, \@a )
The initial call should be of the form
$sum = bal_add( 0, $#numlist, \@numlist );