Skip to content

Instantly share code, notes, and snippets.

@rcanepa
Last active August 29, 2015 14:15
Show Gist options
  • Save rcanepa/5505446c290572a86bec to your computer and use it in GitHub Desktop.
Save rcanepa/5505446c290572a86bec to your computer and use it in GitHub Desktop.
Python Merge Sort
import random
def merge(left_arr, right_arr):
"""
Receives two ordered lists and returns a ordered
list created from the merge of the other two.
:param left_arr: ordered list
:param right_arr: ordered list
:return: ordered list created from the merge of left_arr and right_arr
"""
result = []
lc, rc = 0, 0
while lc < len(left_arr) and rc < len(right_arr):
if left_arr[lc] <= right_arr[rc]:
result.append(left_arr[lc])
lc += 1
else:
result.append(right_arr[rc])
rc += 1
while lc < len(left_arr):
result.append(left_arr[lc])
lc += 1
while rc < len(right_arr):
result.append(right_arr[rc])
rc += 1
return result
def merge_sort(unordered_list):
if len(unordered_list) <= 1:
return unordered_list
else:
left_array = unordered_list[:len(unordered_list)/2]
right_array = unordered_list[len(unordered_list)/2:]
left_array = merge_sort(left_array)
right_array = merge_sort(right_array)
unordered_list = merge(left_array, right_array)
return unordered_list
arr = random.sample(range(1000), 10)
print arr
print merge_sort(arr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment