简体   繁体   English

递归在Mergesort算法(Python)中如何工作?

[英]How does the recursive work in the Mergesort algorithms (Python)?

Here is my code (python 2.7): 这是我的代码(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]. 我苦苦挣扎的是,我不知道为什么在输出的第18行中,左半部分突然变成[26,54]。 I know it is recursive, so should it be [54,26]? 我知道它是递归的,应该是[54,26]吗? and so the right half should be [93, 17]?(line 19 output) 所以右半部分应该是[93,17]?(第19行的输出)

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]? [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]. 左半部分突然变成[26,54]。

It's not suddenly. 不是突然的。 The recursive method call returned back up the call stack 递归方法调用返回了备份堆栈

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM