Created
November 15, 2013 17:46
-
-
Save jakepruitt/7488537 to your computer and use it in GitHub Desktop.
Code Challenge 11/15/2013
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // A utility method that finds the sum of numbers at odd indexes within a sub- | |
| // array starting with startIndex and ending at endIndex | |
| public static int computeSumAtOdd(int[] numbers, int startIndex, int endIndex) | |
| { | |
| if (startIndex == endIndex) // base case: array of size 1, returns number if index odd | |
| { | |
| if (startIndex%2 == 1) | |
| return numbers[startIndex]; | |
| else | |
| return 0; | |
| } | |
| else // recursion: return the sum of odd-index numbers in right half and left half | |
| { | |
| int midIndex = (startIndex + endIndex)/2; | |
| int leftSumAtOdd = computeSumAtOdd(numbers, startIndex, midIndex); | |
| int rightSumAtOdd = computeSumAtOdd(numbers, midIndex+1, endIndex); | |
| return leftSumAtOdd + rightSumAtOdd; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment