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 1f25193

Browse files
authored
Create Merge_Sort.py
1 parent 915d4cf commit 1f25193

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

‎Sorting_Algorithms/Merge_Sort.py‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Merge Sorting Algorithm
2+
arr = [2,4,1,-9,5,32,-55]
3+
4+
def merge(l: list, r: list, arr: list) -> None:
5+
i,j,k= 0,0,0
6+
while i<len(l) and j<len(r):
7+
if l[i] < r[j]:
8+
arr[k] = l[i]
9+
i += 1
10+
else:
11+
arr[k] = r[j]
12+
j += 1
13+
14+
k += 1
15+
16+
while i<len(l):
17+
arr[k] = l[i]
18+
k += 1
19+
i += 1
20+
21+
while j < len(r):
22+
arr[k] = r[j]
23+
k += 1
24+
j += 1
25+
26+
27+
def mergesort(arr: list, n: int):
28+
if n < 2:
29+
return
30+
mid = n//2
31+
# Left sublist
32+
l = arr[:mid]
33+
# Right sublist
34+
r = arr[mid:]
35+
# Call mergesort on the left sublist
36+
mergesort(l, len(l))
37+
# Call mergesort on the right sublist
38+
mergesort(r, len(r))
39+
# Merge both the left and right sublist into the original array
40+
merge(l,r, arr)
41+
42+
# Driver Code
43+
mergesort(arr, len(arr))
44+
print(f'After Sorting: {arr}')

0 commit comments

Comments
(0)

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