How to reverse array in Swift without using “.reverse()”?

后端 未结 21 1828
清歌不尽
清歌不尽 2020-12-08 20:14

I have array and need to reverse it without Array.reverse method, only with a for loop.

var names:[String] = [\"Apple\", \"Microsof         


        
21条回答
  •  余生分开走
    2020-12-08 21:04

    // Swap the first index with the last index.
    // [1, 2, 3, 4, 5] -> pointer on one = array[0] and two = array.count - 1
    // After first swap+loop increase the pointer one and decrease pointer two until
    // conditional is not true. 
    
    func reverseInteger(array: [Int]) -> [Int]{
            var array = array
            var first = 0
            var last = array.count - 1
            while first < last {
                array.swapAt(first, last)
                first += 1
                last -= 1
            }
            return array
        }
    
    input-> [1, 2, 3, 4, 5] return->[5, 4, 3, 2, 1]
    

提交回复
热议问题