We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
2 parents e230675 + d72eeee commit 880475dCopy full SHA for 880475d
1 file changed
SearchAlgorithms/interpolationSearch.js
@@ -0,0 +1,33 @@
1
+/**
2
+ * `arr` must be sorted in ascending order.
3
+ *
4
+ * Returns the index of `target` in `arr`, or -1 if not found.
5
+ * @param arr - array of integers
6
+ * @param target - integer
7
+ */
8
+function interpolationSearch(arr, target) {
9
+ if (!arr || !arr.length) {
10
+ return -1;
11
+ }
12
+
13
+ var low = 0;
14
+ var high = arr.length - 1;
15
16
+ while (
17
+ arr[high] !== arr[low]
18
+ && target >= arr[low]
19
+ && target <= arr[high]
20
+ ) {
21
+ var mid = low + Math.floor(((target - arr[low]) * (high - low) / (arr[high] - arr[low])));
22
23
+ if (arr[mid] < target) {
24
+ low = mid + 1;
25
+ } else if (target < arr[mid]) {
26
+ high = mid - 1;
27
+ } else {
28
+ return mid;
29
30
31
32
+ return target === arr[low] ? low : -1;
33
+}
0 commit comments