Skip to content

Commit 9e64ed0

Browse files
Added code for ternary search
1 parent 57aa60e commit 9e64ed0

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

Go/searching/searching_impl.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ func TestSearching() {
2424
case 2:
2525
result = binarySearch(arr, m)
2626
break
27+
case 3:
28+
result = ternarySearch(0, len(arr)-1, m, arr)
29+
break
2730
}
2831
fmt.Println("Found at index: ", result)
2932
}

Go/searching/ternary.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package searching
2+
3+
func ternarySearch(l, r, x int, arr []int) int {
4+
if r >= l {
5+
mid1 := l + (r-l)/3
6+
mid2 := r - (r-l)/3
7+
if arr[mid1] == x {
8+
return mid1
9+
}
10+
if arr[mid2] == x {
11+
return mid2
12+
}
13+
if x < arr[mid1] {
14+
return ternarySearch(l, mid1-1, x, arr)
15+
}
16+
if x > arr[mid2] {
17+
return ternarySearch(mid2+1, r, x, arr)
18+
}
19+
return ternarySearch(mid1+1, mid2-1, x, arr)
20+
}
21+
return -1
22+
}

0 commit comments

Comments
 (0)