Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Commit

Permalink
Ternary search in Swift (#5773)
Browse files Browse the repository at this point in the history
Co-authored-by: Riyazul555 <riyazulislam2003@gmail.com>
Co-authored-by: Ritesh Kokam <61982298+RiteshK-611@users.noreply.github.com>
  • Loading branch information
3 people committed Jul 5, 2024
1 parent 054e2b7 commit 03841a6
Showing 1 changed file with 37 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import Foundation

func ternarySearch(_ array: [Int], _ value: Int, _ left: Int, _ right: Int) -> Int {
if right >= left {
let partitionSize = (right - left) / 3
let mid1 = left + partitionSize
let mid2 = right - partitionSize

if array[mid1] == value {
return mid1
}
if array[mid2] == value {
return mid2
}

if value < array[mid1] {
return ternarySearch(array, value, left, mid1 - 1)
} else if value > array[mid2] {
return ternarySearch(array, value, mid2 + 1, right)
} else {
return ternarySearch(array, value, mid1 + 1, mid2 - 1)
}
}
return -1
}

// Example usage
let sortedArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let valueToSearch = 7

let result = ternarySearch(sortedArray, valueToSearch, 0, sortedArray.count - 1)

if result != -1 {
print("Element found at index \(result)")
} else {
print("Element not found in the array")
}

0 comments on commit 03841a6

Please sign in to comment.