📜  迭代合并排序的Python程序

📅  最后修改于: 2021-04-26 05:37:04             🧑  作者: Mango

以下是合并排序的典型递归实现,该实现使用最后一个元素作为枢轴。

Python
# Recursive Python Program for merge sort
  
def merge(left, right):
    if not len(left) or not len(right):
        return left or right
  
    result = []
    i, j = 0, 0
    while (len(result) < len(left) + len(right)):
        if left[i] < right[j]:
            result.append(left[i])
            i+= 1
        else:
            result.append(right[j])
            j+= 1
        if i == len(left) or j == len(right):
            result.extend(left[i:] or right[j:])
            break 
  
    return result
  
def mergesort(list):
    if len(list) < 2:
        return list
  
    middle = len(list)/2
    left = mergesort(list[:middle])
    right = mergesort(list[middle:])
  
    return merge(left, right)
      
seq = [12, 11, 13, 5, 6, 7]
print("Given array is")
print(seq); 
print("\n")
print("Sorted array is")
print(mergesort(seq))
  
# Code Contributed by Mohit Gupta_OMG 
Please refer complete article on Iterative Merge Sort for more details!