2017-09-09 1 views
0

Voici mon code (python 2.7):Comment fonctionne la récursive dans les algorithmes 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) 

Et ma sortie est la suivante:

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

Ce que je lutte avec est que je ne sais pas pourquoi la ligne 18 de la sortie , la moitié gauche devient soudainement [26,54]. Je sais que c'est récursif, alors devrait-il être [54,26]? et donc la moitié droite devrait être [93, 17]? (ligne 19 sortie)

Est-ce que quelqu'un a une idée? Merci beaucoup!

Répondre

0

Je sais qu'il est récursive, donc ce devrait être ...

Le fait qu'il est récursive n'affecte pas le numéro de commande du tout. La logique interne fait

[54,26]?

Nope. Votre logique a ordonné aux nombres en ordre croissant

# 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 

la moitié gauche devient soudainement [26,54].

Ce n'est pas soudainement. L'appel de méthode récursif a renvoyé la pile d'appels