forked from ChrisMayfield/ThinkJava2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecursive.java
More file actions
37 lines (31 loc) · 1.09 KB
/
Copy pathRecursive.java
File metadata and controls
37 lines (31 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Search algorithms for arrays of cards.
*/
public class Recursive {
/**
* Binary search (recursive version).
*/
public static int binarySearch(Card[] cards, Card target,
int low, int high) {
System.out.println(low + ", " + high);
if (high < low) {
return -1;
}
int mid = (low + high) / 2; // step 1
int comp = cards[mid].compareTo(target);
if (comp == 0) { // step 2
return mid;
} else if (comp < 0) { // step 3
return binarySearch(cards, target, mid + 1, high);
} else { // step 4
return binarySearch(cards, target, low, mid - 1);
}
}
public static void main(String[] args) {
Card[] cards = makeDeck();
Card jack = new Card(11, 0);
System.out.println("Recursive binary search");
System.out.println(binarySearch(cards, jack, 0, 51));
System.out.println();
}
}