2017-09-09 66 views
0

這裏是我的代碼(蟒蛇2.7):Mergesort算法(Python)中的遞歸工作如何?

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) 

而且我的輸出如下:

`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]` 

我掙扎的是,我不知道爲什麼在輸出線18 ,左半場突然變成[26,54]。我知道它是遞歸的,所以它應該是[54,26]?所以右半部分應該是[93,17]?(第19行輸出)

有沒有人有任何想法?非常感謝!

回答

0

我知道這是遞歸的,所以它應該是...

,它是遞歸的,不影響排序在所有數的事實。內部邏輯確實

[54,26]?

沒有。你的邏輯升序

# 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 

左半突然變[26,54]排列的數字。

這不是突然。遞歸方法調用返回調用堆棧