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 3342970

Browse files
merge sort
1 parent 453848f commit 3342970

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

‎Sorting Algorithms/Merge Sort/README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# MERGE SORT
2+
3+
- Merge sort is a recursive algorithm.
4+
- It starts to divide an array until it divides it into sub-arrays with dimensions of 2.
5+
- Then combine by starting the order from the smallest subarray.
6+
<img src="https://www.101computing.net/wp/wp-content/uploads/Merge-Sort-Algorithm.png" />
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# merge sort
2+
3+
def merge_sort(arr):
4+
if len(arr) > 1:
5+
mid = int(len(arr)/2)
6+
left_half = arr[:mid]
7+
right_half = arr[mid:]
8+
9+
merge_sort(left_half)
10+
merge_sort(right_half)
11+
12+
i = 0 # for left half
13+
j = 0 # for right half
14+
k = 0 # all list
15+
16+
while i < len(left_half) and j < len(right_half):
17+
if left_half[i] < right_half[j]:
18+
arr[k] = left_half[i]
19+
i += 1
20+
else:
21+
arr[k] = right_half[j]
22+
j += 1
23+
k = k + 1
24+
25+
while i < len(left_half):
26+
arr[k] = left_half[i]
27+
i += 1
28+
k += 1
29+
30+
while j < len(right_half):
31+
arr[k] = right_half[j]
32+
j += 1
33+
k += 1
34+
35+
return arr
36+
37+
38+
arr = [3,2,13,4,6,5,7,8,1,20]
39+
print("Output: ", merge_sort(arr) )
40+
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 13, 20]

0 commit comments

Comments
(0)

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