File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+
2
+ import java .util .Arrays ;
3
+ import java .util .Random ;
4
+
5
+ /**
6
+ *
7
+ * @author Gabriele La Greca : https://github.com/thegabriele97
8
+ *
9
+ */
10
+
11
+ public final class IterativeBinarySearch {
12
+
13
+ /**
14
+ * This method implements an iterative version of binary search algorithm
15
+ *
16
+ * @param array a sorted array
17
+ * @param key the key to search in array
18
+ *
19
+ * @return the index of key in the array or -1 if not found
20
+ */
21
+ public static <T extends Comparable <T >> int binarySearch (T [] array , T key ) {
22
+ int l , r , k , cmp ;
23
+
24
+ l = 0 ;
25
+ r = array .length - 1 ;
26
+
27
+ while (l <= r ) {
28
+ k = (l + r ) / 2 ;
29
+ cmp = key .compareTo (array [k ]);
30
+
31
+ if (cmp == 0 ) {
32
+ return k ;
33
+ } else if (cmp < 0 ) {
34
+ r = --k ;
35
+ } else if (cmp > 0 ) {
36
+ l = ++k ;
37
+ }
38
+ }
39
+
40
+ return -1 ;
41
+ }
42
+
43
+ //Only a main method for test purpose
44
+ public static void main (String [] args ) {
45
+ Random rand = new Random ();
46
+ int base = rand .nextInt (1000 );
47
+
48
+ Integer [] array = new Integer [65535 ];
49
+ for (int i = 0 ; i < array .length ; i ++) {
50
+ array [i ] = base + (i + 1 );
51
+ }
52
+
53
+ //Arrays.sort(array); //if needed
54
+ Integer key = base + rand .nextInt (array .length * 2 ); //can generate keys that aren't in array
55
+
56
+ System .out .println (binarySearch (array , key ));
57
+ System .out .println (Arrays .binarySearch (array , key ));
58
+ }
59
+ }
You can’t perform that action at this time.
0 commit comments