Skip to content

Commit

Permalink
reserveCapacity was missing in README (11% faster with it)
Browse files Browse the repository at this point in the history
  • Loading branch information
amakukha committed Feb 1, 2019
1 parent ff780b6 commit fa656f0
Showing 1 changed file with 2 additions and 1 deletion.
3 changes: 2 additions & 1 deletion Merge Sort/README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ func merge(leftPile: [Int], rightPile: [Int]) -> [Int] {

// 2
var orderedPile = [Int]()
orderedPile.reserveCapacity(leftPile.count + rightPile.count)

// 3
while leftIndex < leftPile.count && rightIndex < rightPile.count {
Expand Down Expand Up @@ -115,7 +116,7 @@ This method may look scary, but it is quite straightforward:

1. You need two indexes to keep track of your progress for the two arrays while merging.

2. This is the merged array. It is empty right now, but you will build it up in subsequent steps by appending elements from the other arrays.
2. This is the merged array. It is empty right now, but you will build it up in subsequent steps by appending elements from the other arrays. Since you already know number of elements that will end up in this array, you reserve capacity to avoid reallocation overhead later.

3. This while-loop will compare the elements from the left and right sides and append them into the `orderedPile` while making sure that the result stays in order.

Expand Down

0 comments on commit fa656f0

Please sign in to comment.