Skip to content

Instantly share code, notes, and snippets.

@kayluhb
Last active August 29, 2015 14:11
Show Gist options
  • Save kayluhb/c020eaf093a52036538a to your computer and use it in GitHub Desktop.
Save kayluhb/c020eaf093a52036538a to your computer and use it in GitHub Desktop.
Merge sort!
def merge(arr, arr_ptr, half, half_ptr):
while half_ptr < len(half):
arr[arr_ptr] = half[half_ptr]
half_ptr = half_ptr + 1
array_ptr = array_ptr + 1
return array_ptr
def merge_sort(arr):
print("Splitting ", arr)
if len(arr) > 1:
half_way = len(arr) // 2
left_half = arr[:half_way]
right_half = arr[half_way:]
merge_sort(left_half)
merge_sort(right_half)
left_ptr, right_ptr, arr_ptr = 0, 0, 0
# By the time we make it here, our left and right has been sorted. Woah
while left_ptr < len(left_half) and right_ptr < len(right_half):
if left_half[left_ptr] < right_half[right_ptr]:
arr[arr_ptr] = left_half[left_ptr]
left_ptr = left_ptr + 1
else:
arr[arr_ptr] = right_half[right_ptr]
right_ptr = right_ptr + 1
arr_ptr = arr_ptr + 1
arr_ptr = merge(arr, arr_ptr, left_half, left_ptr)
merge(arr, arr_ptr, right_half, right_ptr)
print("Merging", arr)
integer_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
merge_sort(integer_list)
print(integer_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment