In recursion, a routine solves a small part of a problem itself, divides the problem into smaller pieces, and then calls itself to solve each of the smaller pieces. Recursion is usually called into play when a small part of the problem is easy to solve and a large part is easy to decompose into smaller pieces.

Recursion isn't useful often, but when used judiciously it produces elegant solutions, as in this example in which a sorting algorithm makes excellent use of recursion:

Example 17-5. Java Example of a Sorting Algorithm That Uses Recursion

void QuickSort( int firstIndex, int lastIndex, String [] names ) { if ( lastIndex > firstIndex ...

Start Free Trial

No credit card required