Kotlin recursive function: Find the smallest element in an array
Write a Kotlin recursive function to find the smallest element in an array.
Pre-Knowledge (Before You Start!)
Before solving this exercise, you should understand these concepts:
- Recursion: A recursive function calls itself to solve smaller subproblems until a base case is met.
- Base Case in Recursion: A base case is essential to stop recursion. In this problem, when the index reaches the array size, we return the smallest value found.
- Recursive Case: The function compares the current element with the smallest value found so far and updates it if necessary.
- Array Indexing: Arrays in Kotlin use zero-based indexing, meaning the first element is at index 0.
- Handling Integer Limits: The initial smallest value is set to Int.MAX_VALUE to ensure proper comparisons.
Hints (Try Before Looking at the Solution!)
Here are some hints to help you solve the problem:
- Hint 1: Define a function that takes an array, an index, and a smallest value as parameters.
- Hint 2: Use an if condition to check if the index has reached the array size (base case).
- Hint 3: Compare the current array element with the smallest value found so far.
- Hint 4: Update the smallest value if the current element is smaller.
- Hint 5: Continue recursion until all elements are checked, then return the smallest element.
Sample Solution:
Kotlin Code:
import java.util.Arrays
fun findSmallestElement(array: IntArray, index: Int = 0, smallest: Int = Int.MAX_VALUE): Int {
return if (index == array.size) {
smallest
} else {
val currentElement = array[index]
val updatedSmallest = if (currentElement < smallest) currentElement else smallest
findSmallestElement(array, index + 1, updatedSmallest)
}
}
fun main() {
val array = intArrayOf(7, 3, 8, -1, 0, 4)
val smallest = findSmallestElement(array)
println("Original array elements: ")
println(Arrays.toString(array))
println("Smallest element in the said array: $smallest")
}
Sample Output:
Original array elements: [7, 3, 8, -1, 0, 4] Smallest element in the said array: -1
Explanation:
In the function "findSmallestElement()", we pass an array, an initial index of 0, and a variable smallest to keep track of the current smallest element. At each recursive call, we check if the index is equal to the array size. If it is, we return the current smallest element. Otherwise, we compare the element at the current index with the smallest value. If the current element is smaller, we update the smallest value. We then make a recursive call with the incremented index and the updated smallest value. We continue this process until we get to the end of the array, where we get the smallest element.
Kotlin Editor:
Previous: Calculate the sum of array elements.
Next: Generate permutations of a string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics