Hello. If you don't want to use libraries, you can use this snippet:
/*
* input: [0, 10, 0, 1, 2, 3, 0, 0, 4, 0, 0, 5, 0, 6, 0, 7, 8, 9]
* output: [0, 0, 0, 0, 0, 0, 0, 0, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9]
*/
var array: [Int] = [0, 10, 0, 1, 2, 3, 0, 0, 4, 0, 0, 5, 0, 6, 0, 7, 8, 9]
var startZeroIndex: Int?
for index in array.indices.reversed() {
if array[index] == 0 {
if startZeroIndex == nil {
startZeroIndex = index
}
} else {
if let startIndex = startZeroIndex {
array[startIndex] = array[index]
array[index] = 0
startZeroIndex = startIndex - 1
} else {
continue
}
}
}
print(array)