Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public func binarySearchSortedOffset(arr: [Int], searchedValue: Int) -> Int {
- func hasOffset(l: Int, r: Int) -> Bool {
- return arr[l] > arr[r]
- }
- func isInRange(l: Int, r: Int, searchedValue: Int) -> Bool {
- if hasOffset(l: l, r: r) {
- return searchedValue >= arr[l] || searchedValue <= arr[r]
- } else {
- return searchedValue >= arr[l] && searchedValue <= arr[r]
- }
- }
- var leftIndex = 0
- var rightIndex = arr.count - 1
- if arr.count <= 2 {
- for (index,num) in arr.enumerated() {
- if num == searchedValue {
- return index
- }
- }
- return -1
- }
- while (leftIndex <= rightIndex) {
- if leftIndex == rightIndex {
- if arr[leftIndex] == searchedValue {
- return leftIndex
- } else {
- return -1
- }
- }
- let middle = (leftIndex+rightIndex)/2
- if isInRange(l: leftIndex, r: middle, searchedValue: searchedValue) {
- rightIndex = middle
- } else {
- leftIndex = middle+1
- }
- }
- return -1
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement