Skip to content

Commit 3fc70f1

Browse files
committed
added ternary search
1 parent 1887b93 commit 3fc70f1

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

searches/ternary.search.R

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Ternary Search in R – works on sorted arrays
2+
3+
ternary_search <- function(arr, target) {
4+
l <- 1
5+
r <- length(arr)
6+
while (r >= l) {
7+
mid1 <- l + (r - l) %/% 3
8+
mid2 <- r - (r - l) %/% 3
9+
if (arr[mid1] == target) return(mid1)
10+
if (arr[mid2] == target) return(mid2)
11+
if (target < arr[mid1]) r <- mid1 - 1
12+
else if (target > arr[mid2]) l <- mid2 + 1
13+
else {
14+
l <- mid1 + 1
15+
r <- mid2 - 1
16+
}
17+
}
18+
return(-1)
19+
}
20+
21+
arr <- as.integer(strsplit(readline("Enter sorted integers: "), " ")[[1]])
22+
target <- as.integer(readline("Enter target to search: "))
23+
index <- ternary_search(arr, target)
24+
if (index != -1)
25+
cat("Element found at position:", index, "\n")
26+
else
27+
cat("Element not found.\n")

0 commit comments

Comments
 (0)