1
+ package src .main .java .com .search ;
2
+
3
+ public class InterpolationSearch {
4
+
5
+ /**
6
+ * A linear interpolation search algorithm that finds the position of a
7
+ * target value in an sorted array using its lowest value and highest value.
8
+ *
9
+ * Average time-complexity O(log log n) - uniformly distributed.
10
+ * Worst-case time-complexity O(n) - non-uniformly distributed
11
+ * Worst-case space complexity O(1)
12
+ *
13
+ * @param <T>This is any comparable type
14
+ * @param arr This is the array where the element should be found
15
+ * @param key This is the element to find in the array
16
+ * @return The index of the key in the array
17
+ */
18
+ public <T extends Comparable <T >> int findIndex (T arr [], T key ) {
19
+ return checkCondition (arr , key , 0 , arr .length - 1 );
20
+ }
21
+
22
+ /**
23
+ * @param lowIndex The first and smallest element in the sorted array
24
+ * @param highIndex The last and largest element in the sorted array
25
+ * @return The found key's index in the array through iteration
26
+ */
27
+ private <T extends Comparable <T >> int checkCondition (T arr [], T key , int lowIndex , int highIndex ) {
28
+ boolean conditionOne = lowIndex <= highIndex && key .compareTo (arr [lowIndex ]) >= 0 ;
29
+ boolean conditionTwo = key .compareTo (arr [lowIndex ]) == 0 && key .compareTo (arr [highIndex ]) <= 0 ;
30
+ while (conditionOne || conditionTwo ) {
31
+ int position = getPostion (arr , key , lowIndex , highIndex );
32
+ if (arr [position ].equals (key ))
33
+ return position ;
34
+
35
+ if (arr [position ].compareTo (key ) < 0 )
36
+ lowIndex = position + 1 ;
37
+ else
38
+ highIndex = position - 1 ;
39
+ }
40
+ return -1 ;
41
+ }
42
+
43
+ /**
44
+ * @return The array's current retrieved index position
45
+ */
46
+ private <T > int getPostion (T arr [], T key , int lowIndex , int highIndex ) {
47
+ String startValueString = arr [lowIndex ].toString (); //First convert <T> array element to String
48
+ int startValueInt = Integer .parseInt (startValueString ); //Convert String to int to computate later
49
+ String endValueString = arr [highIndex ].toString ();
50
+ int endValueInt = Integer .parseInt (endValueString );
51
+ String keyValueString = key .toString (); //Repeat for <T> key to later computate
52
+ int keyValueInt = Integer .parseInt (keyValueString );
53
+
54
+ int arrayIndexRangeDiff = highIndex - lowIndex ;
55
+ int arrayHighLowValuesDiff = endValueInt - startValueInt ;
56
+ int keyMinusArrayLowValue = keyValueInt - startValueInt ;
57
+ int position = lowIndex + (((arrayIndexRangeDiff ) / (arrayHighLowValuesDiff ) * (keyMinusArrayLowValue )));
58
+ return position ;
59
+ }
60
+ }
0 commit comments