How to iterate an array from the middle outward (stepping left and right alternately) in Swift

1 Answer

0 votes
import Foundation

func main() {
    // Array to iterate
    let arr: [Int] = [0, 1, 2, 3, 4, 5, 6, 7]
    let n = arr.count

    // Middle index for even-sized arrays
    let mid = n / 2

    // Left starts before the middle, right starts at the middle
    var left = mid - 1
    var right = mid

    // Iterate outward from the middle
    while left >= 0 || right < n {

        if right < n {
            print(arr[right], terminator: " ")
            right += 1
        }

        if left >= 0 {
            print(arr[left], terminator: " ")
            left -= 1
        }
    }
}

main()


/*
run:

4 3 5 2 6 1 7 0

*/

 



answered Jun 29 by avibootz

Related questions

...