1
+ import java .util .Arrays ;
1
2
import java .util .HashMap ;
2
3
import java .util .Random ;
3
4
@@ -131,6 +132,30 @@ public static long fact(int N) {
131
132
return N * fact (N - 1 );
132
133
}
133
134
135
+ /**
136
+ * static method that calls rank to binary search for "key"
137
+ * */
138
+ public static int binarySearch (int key , int [] array ) {
139
+ Arrays .sort (array ); // we need the array to be sorted
140
+ return rank (key , array , 0 , array .length - 1 );
141
+ }
142
+
143
+
144
+ /**
145
+ * static recursive method that implements binary search
146
+ * */
147
+ public static int rank (int key , int [] array , int minIndex , int maxIndex ) {
148
+ if (minIndex > maxIndex ) return -1 ;
149
+ int midIndex = minIndex + (maxIndex - minIndex ) / 2 ;
150
+
151
+ if (array [midIndex ] == key ) return midIndex ;
152
+
153
+ if (array [midIndex ] < key )
154
+ return rank (key , array , midIndex + 1 , maxIndex );
155
+ else
156
+ return rank (key , array , minIndex , maxIndex - 1 );
157
+ }
158
+
134
159
135
160
public static void main (String [] args ) {
136
161
Random generator = new Random ();
@@ -142,6 +167,19 @@ public static void main(String[] args) {
142
167
boolean [][] testTwoDmBooleanArray = new boolean [3 ][2 ];
143
168
int [][] testIntMatrix = new int [3 ][2 ];
144
169
170
+ int [] testIntArray = new int [10 ];
171
+
172
+ testIntArray [0 ] = 5 ;
173
+ testIntArray [1 ] = 7 ;
174
+ testIntArray [2 ] = 6 ;
175
+ testIntArray [3 ] = 9 ;
176
+ testIntArray [4 ] = 3 ;
177
+ testIntArray [5 ] = 8 ;
178
+ testIntArray [6 ] = 2 ;
179
+ testIntArray [7 ] = 4 ;
180
+ testIntArray [8 ] = 1 ;
181
+ testIntArray [9 ] = 10 ;
182
+
145
183
testTwoDmBooleanArray [0 ][0 ] = true ;
146
184
testTwoDmBooleanArray [0 ][1 ] = false ;
147
185
testTwoDmBooleanArray [1 ][0 ] = false ;
@@ -189,5 +227,9 @@ public static void main(String[] args) {
189
227
190
228
System .out .printf ("31!: %d\n " , fact (31 )); // N > 31 causes overflow
191
229
System .out .println ();
230
+
231
+ System .out .println ("- Binary Search: key = 5" );
232
+ System .out .println (binarySearch (5 , testIntArray ));
233
+ System .out .println ();
192
234
}
193
235
}
0 commit comments