To reverse an array, you can iterate over half of the array and swap each element with its corresponding element on the other end of the array. Here’s an example implementation in Kotlin :
fun reverseArray(arr: IntArray): IntArray {
val n = arr.size
for (i in 0 until n / 2) {
val temp = arr[i]
arr[i] = arr[n - i - 1]
arr[n - i - 1] = temp
}
return arr
}
reverseArray
takes an IntArray
as input and returns an IntArray
. The function first gets the length of the array n
. The for
loop iterates over the first half of the array and swaps each element with the corresponding element on the other end of the array. The temp
variable is used to temporarily store the value of the current element being swapped. Finally, the function returns the reversed array.
fun reverseArray(arr: IntArray): IntArray {
val n = arr.size
for (i in 0 until n / 2) {
val temp = arr[i]
arr[i] = arr[n - i - 1]
arr[n - i - 1] = temp
}
return arr
}
fun main(){
val arr = intArrayOf(1, 2, 3, 4, 5)
val reversedArr = reverseArray(arr)
println(reversedArr.contentToString())
}
This code creates an integer array arr
, calls the reverseArray
function to reverse it, and prints the result using contentToString()
. The output of this code will be: [5, 4, 3, 2, 1]