public class BinarySum {
public static void main (String args[]){
int array[] = {1,2,3,4,5,6,7,8};
int sum = binarySum(array , 0 , array.length);
System.out.println(sum);
}
//computing binary sum using recursion
public static int binarySum(int[] array ,int startIndex , int length) {
if(length == 1 )
return array[startIndex];
else
return binarySum(array,startIndex,(int)Math.ceil(length/2.0)) + binarySum(array,startIndex+(int)Math.ceil(length/2.0),(int)Math.floor(length/2.0));
}
}
Recursion trace for binarySum(array , 0 , 8)
No comments:
Post a Comment