|
| 1 | +# Exponential Search in R – efficient search on sorted arrays |
| 2 | + |
| 3 | +#' Performs exponential 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 Exponential search first finds a range where the target may reside by |
| 9 | +#' doubling the index (1, 2, 4, 8, ...), then performs a binary search within that range. |
| 10 | +#' Time complexity: O(log n); requires the array to be sorted in ascending order. |
| 11 | +exponential_search <- function(arr, target) { |
| 12 | + n <- length(arr) |
| 13 | + if (n == 0) return(-1) |
| 14 | + |
| 15 | + # If the first element is the target |
| 16 | + if (arr[1] == target) return(1) |
| 17 | + |
| 18 | + # Find range for binary search by repeated doubling |
| 19 | + i <- 2 |
| 20 | + while (i <= n && arr[i] <= target) { |
| 21 | + i <- i * 2 |
| 22 | + } |
| 23 | + |
| 24 | + low <- max(1, i %/% 2) |
| 25 | + high <- min(i, n) |
| 26 | + |
| 27 | + # Binary search within [low, high] |
| 28 | + return(.binary_search_range(arr, target, low, high)) |
| 29 | +} |
| 30 | + |
| 31 | +# Internal helper: standard binary search on subrange [low, high] |
| 32 | +.binary_search_range <- function(arr, target, low, high) { |
| 33 | + while (low <= high) { |
| 34 | + mid <- low + (high - low) %/% 2 |
| 35 | + if (arr[mid] == target) { |
| 36 | + return(mid) |
| 37 | + } else if (arr[mid] < target) { |
| 38 | + low <- mid + 1 |
| 39 | + } else { |
| 40 | + high <- mid - 1 |
| 41 | + } |
| 42 | + } |
| 43 | + return(-1) |
| 44 | +} |
| 45 | + |
| 46 | +# --- Demonstration (mirrors other search files) --- |
| 47 | +arr <- c(2, 3, 4, 10, 15, 18, 20, 25, 30) # sorted input array |
| 48 | +target <- 18 # value to search |
| 49 | + |
| 50 | +idx <- exponential_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