https://leetcode.com/problems/binary-search/
func search(_ nums: [Int], _ target: Int) -> Int {
var result = -1
for i in 0..<nums.count {
if nums[i] == target {
result = i
}
}
return result
}
func search(_ nums: [Int], _ target: Int) -> Int {
var numscopy = nums
numscopy.sort(by: <)
var low = 0
var high = numscopy.count - 1
var mid = 0
while (low <= high) {
mid = (low + high) / 2
if numscopy[mid] == target {
return mid
}
else if numscopy[mid] > target {
high = mid - 1
}
else {
low = mid + 1
}
}
return -1
func search(_ nums: [Int], _ target: Int) -> Int {
let numscopy = nums.sorted(by: <)
return binarySerach(nums: numscopy, target: target, low: 0, high: numscopy.count - 1)
}
func binarySerach(nums: [Int], target: Int, low: Int, high: Int) -> Int {
if low > high {
return -1
}
let mid = (low + high) / 2
if nums[mid] == target {
return mid
}
else if (nums[mid] > target) {
return binarySerach(nums: nums, target: target, low: low, high: mid - 1)
}
else {
return binarySerach(nums: nums, target: target, low: mid + 1 , high: high)
}
}