How to check if an array is sorted in Kotlin
How to check if an array is sorted in Kotlin.
Here's a step-by-step tutorial on how to check if an array is sorted in Kotlin:
Step 1: Declare an array
To start, declare an array of any type. For example, let's create an array of integers:
val numbers = arrayOf(5, 10, 15, 20, 25)
Step 2: Create a function to check if the array is sorted
Next, create a function that takes an array as a parameter and checks if it is sorted. You can name the function isSorted:
fun isSorted(array: Array<Int>): Boolean {
// implementation goes here
}
Step 3: Compare adjacent elements
Inside the isSorted function, iterate over the elements of the array using a for loop. Compare each element with its adjacent element to check if they are in the correct order:
fun isSorted(array: Array<Int>): Boolean {
for (i in 0 until array.size - 1) {
if (array[i] > array[i + 1]) {
return false
}
}
return true
}
Step 4: Test the function
Now, you can test the isSorted function by passing different arrays to it. Here's an example:
fun main() {
val numbers = arrayOf(5, 10, 15, 20, 25)
val isNumbersSorted = isSorted(numbers)
println("Is numbers sorted? $isNumbersSorted") // Output: Is numbers sorted? true
val letters = arrayOf("a", "b", "c", "z", "y")
val isLettersSorted = isSorted(letters)
println("Is letters sorted? $isLettersSorted") // Output: Is letters sorted? false
}
Step 5: Handle arrays with a custom sorting order
If you want to check if an array is sorted based on a custom sorting order, you can modify the comparison logic inside the isSorted function. For example, let's check if an array of strings is sorted in descending order:
fun isSortedDescending(array: Array<String>): Boolean {
for (i in 0 until array.size - 1) {
if (array[i] < array[i + 1]) {
return false
}
}
return true
}
Now you can test the isSortedDescending function with a different array:
fun main() {
val numbers = arrayOf("z", "y", "x", "a")
val isDescending = isSortedDescending(numbers)
println("Is numbers sorted in descending order? $isDescending") // Output: Is numbers sorted in descending order? true
}
That's it! You now know how to check if an array is sorted in Kotlin.