Check if an array is sorted in Kotlin
Given an array in Kotlin, check if it is sorted or not. An array is sorted in natural order when every array element is greater than its previous element.
The trick is to iterate over the array and compare each set of adjacent elements. The array is considered sorted if the first element is less than the second element for every pair of adjacent elements and unsorted otherwise.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun isSorted(a: IntArray): Boolean { for (i in 0 until a.size - 1) { if (a[i] > a[i + 1]) { return false } } return true } fun main() { val a = intArrayOf(1, 2, 3, 4, 5) println(isSorted(a)) } |
Here’s a recursive procedure for the above code:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun isSorted(a: IntArray?, index: Int): Boolean { // base case if (a == null || a.size <= 1 || index == 1) { return true } return if (a[index - 1] < a[index - 2]) false else isSorted(a, index - 1) } fun main() { val a = intArrayOf(1, 2, 3, 4, 5) println(isSorted(a, a.size)) } |
That’s all about determining whether an array is sorted in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)