33 */
44public class Search {
55
6+ /**
7+ * Make an array of 52 cards.
8+ */
9+ public static Card [] makeDeck () {
10+ Card [] cards = new Card [52 ];
11+ int index = 0 ;
12+ for (int suit = 0 ; suit <= 3 ; suit ++) {
13+ for (int rank = 1 ; rank <= 13 ; rank ++) {
14+ cards [index ] = new Card (rank , suit );
15+ index ++;
16+ }
17+ }
18+ return cards ;
19+ }
20+
21+ /**
22+ * Displays the given deck of cards.
23+ */
24+ public static void printDeck (Card [] cards ) {
25+ for (int i = 0 ; i < cards .length ; i ++) {
26+ System .out .println (cards [i ]);
27+ }
28+ }
29+
630 /**
731 * Sequential search.
832 */
@@ -24,14 +48,14 @@ public static int binarySearch(Card[] cards, Card target) {
2448 while (low <= high ) {
2549 System .out .println (low + ", " + high );
2650
27- int mid = (low + high ) / 2 ; // step 1
51+ int mid = (low + high ) / 2 ; // step 1
2852 int comp = cards [mid ].compareTo (target );
2953
30- if (comp == 0 ) { // step 2
54+ if (comp == 0 ) { // step 2
3155 return mid ;
32- } else if (comp < 0 ) { // step 3
56+ } else if (comp < 0 ) { // step 3
3357 low = mid + 1 ;
34- } else { // step 4
58+ } else { // step 4
3559 high = mid - 1 ;
3660 }
3761 }
@@ -41,40 +65,25 @@ public static int binarySearch(Card[] cards, Card target) {
4165 /**
4266 * Binary search (recursive version).
4367 */
44- public static int binarySearchRec (Card [] cards , Card target ,
45- int low , int high ) {
68+ public static int binarySearch (Card [] cards , Card target ,
69+ int low , int high ) {
4670 System .out .println (low + ", " + high );
4771
4872 if (high < low ) {
4973 return -1 ;
5074 }
51- int mid = (low + high ) / 2 ; // step 1
75+ int mid = (low + high ) / 2 ; // step 1
5276 int comp = cards [mid ].compareTo (target );
5377
54- if (comp == 0 ) { // step 2
78+ if (comp == 0 ) { // step 2
5579 return mid ;
56- } else if (comp < 0 ) { // step 3
57- return binarySearchRec (cards , target , mid + 1 , high );
58- } else { // step 4
59- return binarySearchRec (cards , target , low , mid - 1 );
80+ } else if (comp < 0 ) { // step 3
81+ return binarySearch (cards , target , mid + 1 , high );
82+ } else { // step 4
83+ return binarySearch (cards , target , low , mid - 1 );
6084 }
6185 }
6286
63- /**
64- * Make an array of 52 cards.
65- */
66- public static Card [] makeDeck () {
67- Card [] cards = new Card [52 ];
68- int index = 0 ;
69- for (int suit = 0 ; suit <= 3 ; suit ++) {
70- for (int rank = 1 ; rank <= 13 ; rank ++) {
71- cards [index ] = new Card (rank , suit );
72- index ++;
73- }
74- }
75- return cards ;
76- }
77-
7887 /**
7988 * Demonstrates how to call the search methods.
8089 */
@@ -96,7 +105,8 @@ public static void main(String[] args) {
96105 System .out .println ();
97106
98107 System .out .println ("Recursive binary search" );
99- System .out .println (binarySearch (cards , jack ));
108+ System .out .println (binarySearch (cards , jack , 0 , 51 ));
100109 System .out .println ();
101110 }
111+
102112}
0 commit comments