File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed
Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change 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 " )
You can’t perform that action at this time.
0 commit comments