started work on merge_sort#23
Conversation
| return a_list | ||
| left = [] | ||
| right = [] | ||
| for i in range(len(a_list)): |
There was a problem hiding this comment.
This is an unconventional way of splitting a list in half, and I'm loving it. Nice job.
| else: | ||
| new_list.append(right[0]) | ||
| right = right[1:] | ||
| while left: |
There was a problem hiding this comment.
These next 6 lines can be simplified and made much less expensive using the list.extend method, since all you're doing is adding the remaining elements of left, then the remaining elements of right:
new_list.extend(left)
new_list.extend(right)| while left and right: | ||
| if left[0] < right[0]: | ||
| new_list.append(left[0]) | ||
| left = left[1:] |
There was a problem hiding this comment.
This approach will work, but will be more expensive than necessary because creating a slice of a list will use an additional O(slice size) time and space.
The canonical merge sort implementation uses two separate index pointers for the left and right lists. You could also create two different generators which you only advance using next() when necessary.
| new_list.append(right[right_idx]) | ||
| right_idx += 1 | ||
| while left_idx < len(left): | ||
| new_list.extend([left[left_idx]]) |
There was a problem hiding this comment.
This isn't really what I had in mind. This isn't really how you use list.extend.
You can do this all in a single line:
new_list.extend(left[left_idx:])
new_list.extend(right[right_idx:])
No description provided.