Created
November 27, 2021 19:35
-
-
Save thatswiftguy/355d1e6b7936d3411bd17b580cab91d1 to your computer and use it in GitHub Desktop.
This gist contains few recursion programs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func binarySearchWithRecursion(arr: [Int], target: Int, s: Int, e: Int) -> Int { | |
if s > e { | |
return -1 | |
} | |
if arr[s] == target { | |
return s | |
} | |
let med = e / arr.count | |
if target < arr[med] { | |
return binarySearchWithRecursion(arr: arr, target: target, s: s, e: med - 1) | |
} | |
return binarySearchWithRecursion(arr: arr, target: target, s: med + 1, e: e) | |
} | |
print(binarySearchWithRecursion(arr: [1,4,6,7,8], target: 6, s: 0, e: 5)) | |
func linearSearchWithRecursion(arr: [Int], target: Int, currentIndex: Int = 0) -> Int { | |
if currentIndex == arr.count - 1 { | |
return -1 | |
} | |
if arr[currentIndex] == target { | |
return currentIndex | |
} | |
return linearSearchWithRecursion(arr: arr, target: target, currentIndex: currentIndex + 1) | |
} | |
print(linearSearchWithRecursion(arr: [1,4,5,25,6,34,4], target: 55)) | |
func checkIfArrayIsSorted(arr: [Int], currentIndex: Int = 0) -> Bool { | |
if currentIndex == arr.count - 1 { | |
return true | |
} | |
if arr[currentIndex] > arr[currentIndex + 1] { | |
return false | |
} | |
return checkIfArrayIsSorted(arr: arr, currentIndex: currentIndex + 1) | |
} | |
print(checkIfArrayIsSorted(arr: [1,3,4,7,2])) | |
func countDigits(num: Int) -> Int { | |
if num == 0 { | |
return 0 | |
} | |
return 1 + countDigits(num: num / 10) | |
} | |
print(countDigits(num: 2314)) | |
func countZero(num: Int, count: Int) -> Int { | |
if num == 0 { | |
return count | |
} | |
if num % 10 == 0 { | |
return countZero(num: num / 10, count: count + 1) | |
} | |
return countZero(num: num / 10, count: count) | |
} | |
print(countZero(num: 1000200, count: 0)) | |
func productOfDigits(num: Int) -> Int { | |
if num == 0 { | |
return 1 | |
} | |
return num % 10 * productOfDigits(num: num / 10) | |
} | |
print(productOfDigits(num: 1223)) | |
func sumOfDigits(num: Int) -> Int { | |
if num == 0 { | |
return 0 | |
} | |
return num % 10 + sumOfDigits(num: num / 10) | |
} | |
print(sumOfDigits(num: 123)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment