Skip to content

Commit 304eb46

Browse files
authored
Add Interpolation Search in R (#228)
1 parent 9abffc8 commit 304eb46

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

searches/interpolation_search.r

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# Interpolation Search in R – works on sorted arrays with uniformly distributed values
2+
3+
#' Performs interpolation search on a sorted numeric vector.
4+
#'
5+
#' @param arr Numeric vector sorted in ascending order.
6+
#' @param target Numeric value to search for in arr.
7+
#' @return The 1-based index of target in arr if found; otherwise -1.
8+
#' @details Interpolation search estimates the position of target using
9+
#' linear interpolation, which is efficient on uniformly distributed data.
10+
#' Time complexity: average O(log log n), worst-case O(n). Requires a sorted array.
11+
interpolation_search <- function(arr, target) {
12+
n <- length(arr)
13+
if (n == 0) return(-1)
14+
low <- 1
15+
high <- n
16+
17+
# Guard: if target is outside the bounds, fail early
18+
if (target < arr[low] || target > arr[high]) return(-1)
19+
20+
while (low <= high && target >= arr[low] && target <= arr[high]) {
21+
# Avoid division by zero when all values in range are equal
22+
if (arr[low] == arr[high]) {
23+
if (arr[low] == target) return(low)
24+
return(-1)
25+
}
26+
27+
# Estimate position using linear interpolation
28+
pos <- low + floor((target - arr[low]) * (high - low) / (arr[high] - arr[low]))
29+
30+
# Bounds safety in case of numerical issues
31+
if (pos < low) pos <- low
32+
if (pos > high) pos <- high
33+
34+
if (arr[pos] == target) {
35+
return(pos)
36+
} else if (arr[pos] < target) {
37+
low <- pos + 1
38+
} else {
39+
high <- pos - 1
40+
}
41+
}
42+
43+
return(-1)
44+
}
45+
46+
# --- Demonstration (simple usage, mirrors other search files) ---
47+
arr <- c(10, 20, 30, 40, 50, 60, 70, 80, 90, 100) # sorted input array
48+
target <- 70 # value to search
49+
50+
idx <- interpolation_search(arr, target)
51+
52+
if (idx == -1) {
53+
cat("Element", target, "not found in the array.\n")
54+
} else {
55+
cat("Element", target, "found at position", idx, ".\n")
56+
}

0 commit comments

Comments
 (0)