Here is my code (python 2.7):
def merge_sort(a_list):
print ("Splitting ", a_list)
if len(a_list) > 1:
mid = len(a_list) // 2
left_half = a_list[:mid]
#print left_half
right_half = a_list[mid:]
#print right_half
merge_sort(left_half)
merge_sort(right_half)
i = 0
j = 0
k = 0
print ("Left half is ", left_half)
print ("Right half is ", right_half)
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
a_list[k] = left_half[i]
i = i + 1
else:
a_list[k] = right_half[j]
j = j + 1
k = k + 1
while i < len(left_half):
a_list[k] = left_half[i]
i = i + 1
k = k + 1
while j < len(right_half):
a_list[k] = right_half[j]
j = j + 1
k = k + 1
print("Merging ", a_list)
a_list = [54, 26, 93, 17]
merge_sort(a_list)
print(a_list)
And my output is as follows:
`1.('Splitting ', [54, 26, 93, 17])
2.('Splitting ', [54, 26])
3.('Splitting ', [54])
4.('Merging ', [54])
5.('Splitting ', [26])
6.('Merging ', [26])
7.('Left half is ', [54])
8.('Right half is ', [26])
9.('Merging ', [26, 54])
10.('Splitting ', [93, 17])
11.('Splitting ', [93])
12.('Merging ', [93])
13.('Splitting ', [17])
14.('Merging ', [17])
15('Left half is ', [93])
16.('Right half is ', [17])
17.('Merging ', [17, 93])
18.('Left half is ', [26, 54])
19.('Right half is ', [17, 93])
20.('Merging ', [17, 26, 54, 93])
21.[17, 26, 54, 93]`
What I struggling with is that I don't know why in line 18 of the output, the left half suddenly becomes [26,54]. I know it is recursive, so should it be [54,26]? and so the right half should be [93, 17]?(line 19 output)
Does anyone has any idea? Thank you so much!
I know it is recursive, so should it be...
The fact that it's recursive doesn't affect the number ordering at all. The internal logic does
[54,26]?
Nope. Your logic ordered the numbers in ascending order
# add the left half (the smaller number) to the merged list
if left_half[i] < right_half[j]:
a_list[k] = left_half[i]
i = i + 1
else: # the right half is smaller, so add it
a_list[k] = right_half[j]
j = j + 1
the left half suddenly becomes [26,54].
It's not suddenly. The recursive method call returned back up the call stack
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.