|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | |||||||||
java.lang.Objectorg.apache.commons.functor.example.kata.two.TestBinaryChop
public class TestBinaryChop
Examples of binary search implementations. A binary search algorithm is the same strategy used in that number guessing game, where one player picks a number between 1 and 100, and the second player tries to guess it. Each time the second player guesses a number, the first player tells whether the chosen number is higher, lower or equal to the guess. An effective strategy for this sort of game is always guess the midpoint between what you know to be the lowest and highest possible number. This will find the number in log2(N) guesses (when N = 100, this is at most 7 guesses). For example, suppose the first player (secretly) picks the number 63. The guessing goes like this: P1> I'm thinking of a number between 1 and 100. P2> Is it 50? P1> Higher. P2> 75? P1> Lower. P2> 62? P1> Higher. P2> 68? P1> Lower. P2> 65? P1> Lower. P2> 63? P1> That's it. Dave Thomas's Kata Two asks us to implement a binary search algorithm in several ways. Here we'll use this as an opportunity to consider some common approaches and explore some functor based approaches as well. See http://pragprog.com/pragdave/Practices/Kata/KataTwo.rdoc,v for more information on this Kata.
| Constructor Summary | |
|---|---|
TestBinaryChop()
|
|
| Method Summary | |
|---|---|
void |
testBuiltIn()
In practice, one would most likely use the binary search method already available in java.util.Collections, but that's not really the point of this exercise. |
void |
testIterative()
Here's a basic iterative approach. |
void |
testIterativeWithInvariants()
|
void |
testIterativeWithInvariantsAndAssertions()
|
void |
testRecursive()
A recursive version of that implementation uses method parameters to track the upper and lower bounds. |
void |
testRecursive2()
One fun functional approach is to "slice" up the list as we search, looking at smaller and smaller slices until we've found the element we're looking for. |
void |
testTailRecursive()
We can use the Algorithms.recuse method to implement that as tail recursion. |
void |
testTailRecursive2()
We can do that using tail recursion as well. |
| Methods inherited from class java.lang.Object |
|---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Constructor Detail |
|---|
public TestBinaryChop()
| Method Detail |
|---|
public void testBuiltIn()
public void testIterative()
public void testIterativeWithInvariants()
public void testIterativeWithInvariantsAndAssertions()
public void testRecursive()
public void testTailRecursive()
public void testRecursive2()
public void testTailRecursive2()
|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | |||||||||