Skip to content

Instantly share code, notes, and snippets.

@jakepruitt
Created November 15, 2013 17:46
Show Gist options
  • Select an option

  • Save jakepruitt/7488537 to your computer and use it in GitHub Desktop.

Select an option

Save jakepruitt/7488537 to your computer and use it in GitHub Desktop.
Code Challenge 11/15/2013
// 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