Reverse an array in Kotlin
This article explores different ways to reverse the order of elements in an array in Kotlin.
1. Using reverse() function
In Kotlin, you can use the reverse() extension function to reverse an array. This is demonstrated below:
|
1 2 3 4 5 6 |
fun main() { val arr: Array<Int?> = arrayOf(1, 2, 3, 4, 5) arr.reverse(); println(arr.contentToString()) } |
2. Create Auxiliary Array
Another solution is to create an auxiliary array of the same type and size as the original array. Then fill it with elements from the original array in reverse order. Finally, copy the contents of the auxiliary array into the source array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
inline fun<reified T> reverse(arr: Array<T?>) { val temp = arrayOfNulls<T>(arr.size) for (i in arr.indices) { temp[arr.size - 1 - i] = arr[i] } for (i in arr.indices) { arr[i] = temp[i] } } fun main() { val arr: Array<Int?> = arrayOf(1, 2, 3, 4, 5) reverse(arr) println(arr.contentToString()) } |
3. In-place Implementation
You can avoid the extra space taken by the auxiliary array by modifying the array in-place. We can do this by overwriting the existing array elements. The idea is to read elements from both ends of the array and swap each such pair.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
fun<T> swap(arr: Array<T?>, i: Int, j: Int) { val temp = arr[i] arr[i] = arr[j] arr[j] = temp } fun<T> reverse(arr: Array<T?>) { var low = 0 var high = arr.size - 1 while (low < high) { swap(arr, low, high) low++ high-- } } fun main() { val arr: Array<Int?> = arrayOf(1, 2, 3, 4, 5) reverse(arr) println(arr.contentToString()) } |
4. Recursive Solution
Another plausible way is to use recursion. Here’s a recursive solution:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
fun<T> reverse(arr: Array<T?>, nextIndex: Int) { // base case: empty array or end of the array is reached if (nextIndex == arr.size) return // store next element of the array val value = arr[nextIndex] // reach the end of the array using recursion reverse(arr, nextIndex + 1) // put elements in the call stack back into an array // starting from the beginning arr[arr.size - nextIndex - 1] = value } fun main() { val arr: Array<Int?> = arrayOf(1, 2, 3, 4, 5) reverse(arr, 0) println(arr.contentToString()) } |
That’s all about reversing an array 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 :)