1+ /*
2+ * @Fr4nc3
3+ * Problem2 class
4+ * Programing Q2
5+ */
6+ import java .util .Arrays ;
7+
8+ public class Problem2 {
9+ public static final int ARRAY_SIZE = 5 ;
10+
11+ public static <AnyType extends Comparable <AnyType >> int binarySearch (AnyType [] a , AnyType x ) {
12+ return binarySearch (a , x , 0 , a .length - 1 );
13+ }
14+
15+ public static <AnyType extends Comparable <AnyType >> int binarySearch (AnyType [] a , AnyType x ,
16+ int low , int high ) {
17+ if (low > high ) return -1 ;
18+ int mid = (low + high ) / 2 ;
19+ if (a [mid ].compareTo (x ) == 0 ) return mid ;
20+ else if (a [mid ].compareTo (x ) < 0 )
21+ return binarySearch (a , x , mid + 1 , high );
22+ else // last possibility
23+ return binarySearch (a , x , low , mid - 1 );
24+ }
25+
26+ public static void main (String [] args ) {
27+
28+ Rectangle [] a = new Rectangle [ARRAY_SIZE ];
29+ //create an empty rectangle that we will use to find after the sort
30+ Rectangle findRectangle = new Rectangle (0 , 0 );
31+ for (int i = 0 ; i < ARRAY_SIZE ; ++i ) {
32+ // generate dimensions randomly
33+ int width = (int ) (Math .random () * 50 + 1 );
34+ int length = (int ) (Math .random () * 50 + 1 );
35+
36+ // we give real dimension to our rectangle
37+ // this means it always will appear in this test case
38+ if (findRectangle .getLength () == 0 ) {
39+ findRectangle .setLength (length );
40+ findRectangle .setWidth (width );
41+ }
42+
43+ a [i ] = new Rectangle (length , width );
44+ }
45+ Arrays .sort (a );
46+ System .out .println ("New Array Rectangles Dimensions:\n " );
47+
48+ for (int i = 0 ; i < ARRAY_SIZE ; ++i ) {
49+ System .out .println ("Rectangle " + i );
50+ System .out .println (a [i ].toString () + "\n " );
51+ }
52+
53+ System .out .println ("Found Rectangle" + findRectangle .toString ());
54+ System .out .println ("Rectangle Index: " + binarySearch (a , findRectangle ));
55+
56+ /*
57+ * Second test we create a rectangle with random dimensions and
58+ * it may or may not exist
59+ * */
60+ int width = (int ) (Math .random () * 50 + 1 );
61+ int length = (int ) (Math .random () * 50 + 1 );
62+ Rectangle doExistRectangle = new Rectangle (length , width );
63+
64+ System .out .println ("\n \n New Rectangle to find" + doExistRectangle .toString ());
65+ System .out .println ("Rectangle Index? " + binarySearch (a , doExistRectangle ));
66+
67+ }
68+ }
0 commit comments