Skip to content

Instantly share code, notes, and snippets.

@jeffchiucp
Last active July 30, 2018 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffchiucp/9dc2a5108429c4222fe4b2a25e35c778 to your computer and use it in GitHub Desktop.
Save jeffchiucp/9dc2a5108429c4222fe4b2a25e35c778 to your computer and use it in GitHub Desktop.
Merge two sorted lists
#
# 2g. Merge two sorted lists
#
# Input: lst1 {List}
# Input: lst2 {List}
# Output: {List}
#
# Example: merge([1, 4, 7], [2, 3, 6, 9]) => [1, 2, 3, 4, 6, 7, 9]
#
def merge(left, right):
# Time Complexity: O(N) solution
# merge 2 list
# divide and conquer
# combine - step2
("\n"
" while left_index is not the length of left_array and right_index is not the length of right_array\n"
" if left_array[left_index] < right_array[right_index]\n"
" add left_array[left_index] to merged array\n"
" left_index + 1\n"
" else\n"
" add right_array[right_index] to merged_array\n"
" right_index + 1 ")
# if we've passed the end of either list, then extend the sorted list
# with what remains in the other
left_pointer = 0
right_pointer = 0
sorted_list = []
# I fix the bug with left or right array is empty
# When left or right is an empty list this will break with an IndexError.
while len(sorted_list) < len(left) + len(right):
if right_pointer >= len(right):
sorted_list.extend(left[left_pointer:])
break
if left_pointer >= len(left):
sorted_list.extend(right[right_pointer:])
break
left_item = left[left_pointer]
right_item = right[right_pointer]
if left_item < right_item:
sorted_list.append(left_item)
left_pointer += 1
else:
sorted_list.append(right_item)
right_pointer += 1
return sorted_list
@jeffchiucp
Copy link
Author

I want to also support different length array, you should do so explicitly.

@jeffchiucp
Copy link
Author

Update the code to handle edge cases When left or right is an empty list this will break with an IndexError

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment