FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
python-algorithms/algorithms/sort/merge_sort.py at master · ilyvsc/python-algorithms · GitHub
ilyvsc
/
python-algorithms
Public
forked from
keon/algorithms
Notifications
You must be signed in to change notification settings
Fork
0
Star
1
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
python-algorithms
/
algorithms
/
sort
/
merge_sort.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
40 lines (35 loc) · 1.37 KB
Breadcrumbs
python-algorithms
/
algorithms
/
sort
/
merge_sort.py
Copy path
File metadata and controls
40 lines (35 loc) · 1.37 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def
merge_sort
(
arr
):
""" Merge Sort
Complexity: O(n log(n))
"""
# Our recursive base case
if
len
(
arr
)
<=
1
:
return
arr
mid
=
len
(
arr
)
//
2
# Perform merge_sort recursively on both halves
left
,
right
=
merge_sort
(
arr
[:
mid
]),
merge_sort
(
arr
[
mid
:])
# Merge each side together
# return merge(left, right, arr.copy()) # changed, no need to copy, mutate inplace.
merge
(
left
,
right
,
arr
)
return
arr
def
merge
(
left
,
right
,
merged
):
""" Merge helper
Complexity: O(n)
"""
left_cursor
,
right_cursor
=
0
,
0
while
left_cursor
<
len
(
left
)
and
right_cursor
<
len
(
right
):
# Sort each one and place into the result
if
left
[
left_cursor
]
<=
right
[
right_cursor
]:
merged
[
left_cursor
+
right_cursor
]
=
left
[
left_cursor
]
left_cursor
+=
1
else
:
merged
[
left_cursor
+
right_cursor
]
=
right
[
right_cursor
]
right_cursor
+=
1
# Add the left overs if there's any left to the result
for
left_cursor
in
range
(
left_cursor
,
len
(
left
)):
merged
[
left_cursor
+
right_cursor
]
=
left
[
left_cursor
]
# Add the left overs if there's any left to the result
for
right_cursor
in
range
(
right_cursor
,
len
(
right
)):
merged
[
left_cursor
+
right_cursor
]
=
right
[
right_cursor
]
# Return result
# return merged # do not return anything, as it is replacing inplace.
Back
|
FazBrowse Home
|
New Git URL