I’ve had this question come up a few times in the past on interviews, how would
you merge two sorted arrays and keep their sort order intact? The easy / PHP
answer is to simply use
array_merge() and then
sort() the resulting array.
Technically this works but the whole point behind the question is to see if you
can work through the logic itself.
Someone recently gave me a great analogy for merging two sorted arrays. They said, think of it like you have 2 decks of cards, how would you manage that? With two decks of cards, the first thing to do would be to flip over one card from each stack. Once you have a card from each stack, you an compare the two cards and determine which one is smaller. That smaller card can then be placed into a new deck and another card can be flipped over. Continue the process until both decks are exhausted.
Here’s how the code would look:
It’s not that pretty, but it gets the job done. Got a more elegant solution
sort()? Feel free to share it below in