Skip to content

Commit 4eab76d

Browse files
author
Philip Guo
committed
bah
1 parent d151fb3 commit 4eab76d

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

‎questions/buggy-mergesort.txt‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
Name:
2+
Debugging: Mergesort
3+
4+
Question:
5+
6+
Make the given mergesort function work properly.
7+
8+
Hint:
9+
Focus on the merge function.
10+
11+
Solution:
12+
The merge function must append all of the 'leftovers' from left and
13+
right onto result.
14+
15+
Skeleton:
16+
17+
# Adapted from: http://en.literateprograms.org/Merge_sort_(Python)
18+
19+
def merge(left, right):
20+
result = []
21+
i ,j = 0, 0
22+
while i < len(left) and j < len(right):
23+
if left[i] <= right[j]:
24+
result.append(left[i])
25+
i += 1
26+
else:
27+
result.append(right[j])
28+
j += 1
29+
return result
30+
31+
def mergesort(list):
32+
if len(list) < 2:
33+
return list
34+
else:
35+
middle = len(list) / 2
36+
left = mergesort(list[:middle])
37+
right = mergesort(list[middle:])
38+
return merge(left, right)
39+
40+
41+
Test:
42+
input = [4,3,2,1]
43+
result = mergesort(input)
44+
45+
Expect:
46+
result = [1,2,3,4]
47+

0 commit comments

Comments
 (0)