Solution from the book uses insert method to reverse the array which is add at position 0 then shift all the elements to the right 1 time which is O(n).
func reversed(_ array: [Int]) -> [Int] {
var newArray: [Int] = []
for item in array {
newArray.insert(item, at: 0)
}
return newArray
}
Isn’t it better to use append method instead ?
func kreversed(_ array: [Int]) -> [Int] {
var newArray: [Int] = []
let position = array.count - 1
for index in array{
newArray.append(array[position - index])
}
return newArray
}
Hi! Thanks for sharing surepic. Yes, your version is more efficient!
You can it even a little faster by calling
newArray.reserveCapacity(array.count)
That way append won’t need to worry about doing the allocations. Depending on the size it might have to do multiple reallocations and copies if it doesn’t know the size.
By the way, if you cheat and use the standard library (which you should in practice!) you can do it like so
The method reversed() is O(1) and returns a lazy ReversedCollection<Array<Int>>. Then you initialize that with an array that iterates through the reverse collection (as you have done) and constructs the Array in one go. It has the same good performance characteristics as your hand rolled loop.
count is O(1) for RandomAccessCollection. It is actually implemented as endIndex - startIndex because collections might not start from zero, as is the case with ArraySlice.