How to reverse an array using recursion ?

[Question] : Reverse array using recursion Example: [1,2,3] = [3,2,1]. Approach #1 using two variables : –
// Question reverse the string using recursion
// Here we are just swapping right with left & increase the left & right elements
func reverseArrayUsingRecursion(inArray: inout [Int],
                   rightElement: inout Int,
                   leftElement: inout Int) {
    
    if rightElement >= leftElement {return}
    inArray.swapAt(rightElement, leftElement)
    rightElement += 1
    leftElement -= 1
    reverseArrayUsingRecursion(inArray: &inArray,
                  rightElement: &rightElement,
                  leftElement: &leftElement)
}

var inArray = [1, 2, 3, 4]
var rightElement = 0
var leftElement = inArray.count - 1
reverseArrayUsingRecursion(inArray: &inArray, rightElement: &rightElement, leftElement: &leftElement)
print(inArray) // prints [4, 3, 2, 1]
// Approach#2: Using single pointer/variable so we written base case which blocks on n/2, we are just increasing the element by +1 on every recursion till half of the array.
func reverseArrayUsingRecursion2(inArray: inout [Int],
                                 startIndex: inout Int) {
    
    if startIndex >= inArray.count/2 {return}
    inArray.swapAt(startIndex, inArray.count-startIndex-1)
    startIndex += 1
    reverseArrayUsingRecursion2(inArray: &inArray,
                                startIndex: &startIndex)
}

var inArray2 = [1, 2, 3, 4]
var startIndex = 0
reverseArrayUsingRecursion2(inArray: &inArray2, startIndex: &startIndex)
print(inArray2)

Leave a Comment

Your email address will not be published. Required fields are marked *