AP - Recursion - Class Material
AP - Recursion - Class Material
Recursion is when a method calls itself. See the example method below.
public static void neverEnd()
1
{
2
System.out.println("This is the method that never ends!");
3
neverEnd();
4
}
5
This method will print out “This is the method that never ends!” and then call itself,
which will print out the message again, and then call itself, and so on. This is
called infinite recursion, which is a recursion that never ends. Of course, this particular
method is not very useful.
Merge Sort
import java.util.Arrays;
private static void mergeSortHelper(int[] elements, int from, int to, int[] temp)
{
if (from < to)
{
int middle = (from + to) / 2;
mergeSortHelper(elements, from, middle, temp);
mergeSortHelper(elements, middle + 1, to, temp);
merge(elements, from, middle, to, temp);
}
}
private static void merge(int[] elements, int from, int mid, int to, int[] temp)
{
int i = from;
int j = mid + 1;
int k = from;