Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e42766b

Browse files
author
Muh. Angga Muttaqien
committed
add merge sort
1 parent 80304d7 commit e42766b

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

‎sorting/merge-sort.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
2+
def merge_sort(collection):
3+
4+
length = len(collection)
5+
6+
if length > 1:
7+
midpoint = length // 2
8+
left_half = merge_sort(collection[:midpoint])
9+
right_half = merge_sort(collection[midpoint:])
10+
i = 0
11+
j = 0
12+
k = 0
13+
left_length = len(left_half)
14+
right_length = len(right_half)
15+
16+
while i < left_length and j < right_length:
17+
if left_half[i] < right_half[j]:
18+
collection[k] = left_half[i]
19+
i += 1
20+
else:
21+
collection[k] = right_half[j]
22+
j += 1
23+
k += 1
24+
25+
while i < left_length:
26+
collection[k] = left_half[i]
27+
i += 1
28+
k += 1
29+
30+
while j < right_length:
31+
collection[k] = right_half[j]
32+
j += 1
33+
k += 1
34+
35+
return collection
36+
37+
38+
def main():
39+
print("=== Merge Sort (Algorithm) - An efficient, general-purpose, comparison-based sorting algorithm which most implementations produce a stable sort. Merge-sort is a divide and conquer algorithm")
40+
numbers = raw_input("Enter numbers separated by a comma: ")
41+
unsorted = [int(item) for item in numbers.split(',')]
42+
print(merge_sort(unsorted))
43+
44+
if __name__=='__main__':
45+
main()

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /