mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-22 08:21:12 -04:00
Create merge_sort.py
This commit is contained in:
parent
384b79adf8
commit
c3e12c40a4
1 changed files with 34 additions and 0 deletions
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…
Add table
Add a link
Reference in a new issue