Thursday, 31 July 2014

Summing 2dArray using Recursion


This algortihm uses summing a 1d array using recursion - see -



/*
* Thid programme uses Binary Sum  algo to recursively calculate sum of 2d array using recursion
*/

public class BinarySum {
public static void main(String args[]) {

int array[][] = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 }, { 9, 10 } };

int sum = binarySum2d(array, array.length, array[0].length);

System.out.println(sum);
}

// evalauate each row recursively and send to binarySum1d for calculating
// sum
private static int binarySum2d(int[][] array, int rows, int columns) {

if (rows == 0)
return 0;

// calculate sum for each row
return binarySum2d(array, rows - 1, columns)
+ binarySum1d(array[rows - 1], 0, columns);

}

// computing binary sum of 1d array using recursion
public static int binarySum1d(int array[], int startIndex, int length) {

if (length == 1)
return array[startIndex];
else
return binarySum1d(array, startIndex, (int) Math.ceil(length / 2.0))
+ binarySum1d(array,
startIndex + (int) Math.ceil(length / 2.0),
(int) Math.floor(length / 2.0));
}

}

No comments:

Post a Comment