mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 12:16:14 -04:00
Create merge_sort.py
This commit is contained in:
parent
384b79adf8
commit
c3e12c40a4
34
sorting/merge_sort.py
Normal file
34
sorting/merge_sort.py
Normal file
@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# author: bt3gl
|
||||
|
||||
|
||||
def merge_sort(array):
|
||||
|
||||
# part 1: recursively divide the array into subarrays
|
||||
if len(array) < 2:
|
||||
return array
|
||||
|
||||
mid = len(array) // 2
|
||||
left = merge_sort(array[:mid])
|
||||
right = merge_sort(array[mid:])
|
||||
|
||||
# part 2: merge the subarrays
|
||||
result = []
|
||||
i, j = 0, 0
|
||||
|
||||
while i < len(left) and j < len(right):
|
||||
if left[i] <= right[j]:
|
||||
result.append(left[i])
|
||||
i +=1
|
||||
else:
|
||||
result.append(right[j])
|
||||
j +=1
|
||||
|
||||
if left[i:]:
|
||||
result.extend(left[i:])
|
||||
if right[j:]:
|
||||
result.extend(right[j:])
|
||||
|
||||
return result
|
||||
|
Loading…
x
Reference in New Issue
Block a user