2021年1月7日星期四

Merge sort problem, the code is wrong in the recursion procedure

I am working on merge sort, which is written in a recursive procedure, but it is not right, I print every procedure

import math  def merge_sort(A):      l=len(A)      if l>1:          merge_sort(A[:math.floor(l/2)])          merge_sort(A[math.floor(l/2):])          merge(A)  def merge(A):      l=len(A)      half1=A[:math.floor(l/2)]      half2=A[math.floor(l/2):]      l1=len(half1)      l2=len(half2)      B=[]      for i in range(l):          if l1 == 0:              B.append(half2[len(half2)-l2])              l2-=1          elif l2 == 0:              B.append(half1[len(half1)-l1])              l1-=1          elif half1[len(half1)-l1] <= half2[len(half2)-l2]:              B.append(half1[len(half1)-l1])              l1-=1          elif half2[len(half2)-l2] < half1[len(half1)-l1]:              B.append(half2[len(half2)-l2])              l2-=1      for i in range(l):          A[i]=B[i]      print(A)  A=[5,3,2,8,6,7,11,9,111,3]  merge_sort(A)    

In order to find where is wrong, I print out every step, which gives me

[3, 5]  [6, 8]  [2, 8, 6]  [2, 5, 3, 8, 6]  [7, 11]  [3, 111]  [9, 111, 3]  [7, 9, 11, 111, 3]  [5, 3, 2, 7, 8, 6, 11, 9, 111, 3]  
https://stackoverflow.com/questions/65622882/merge-sort-problem-the-code-is-wrong-in-the-recursion-procedure January 08, 2021 at 11:03AM

没有评论:

发表评论