Merge Sort with Recursion and Iteration
阿新 • • 發佈:2018-11-05
Merge Sort
Following is a typical recursive implementation of Merge Sort:
def mergeSorting(self,arry):
def two_part_sort(left,right):
result = []
i,j = 0,0
while i < len(left) and j < len(right):
if left[i] <= right[ j]:
result += [left[i]]
i += 1
else:
result += [right[j]]
j +=1
result += left[i:]
result += right[j:]
return result
def msort_rec(arry):
n = len(arry)
mid = n // 2
if mid < 1:
return arry
left = msort_rec(arry[:mid])
right = msort_rec(arry[mid:])
result = two_part_sort(left, right)
return result
return msort_rec(arry)
Following is a iterative implementation of Merge Sort, like a binary search tree:
def mergeSorting2(self,arry):
def two_part_sort(left,right):
result = []
i,j = 0,0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result += [left[i]]
i += 1
else:
result += [right[j]]
j +=1
result += left[i:]
result += right[j:]
return result
def binary_function(arry):
result = []
i = 0
while i <= len(arry)-2:
result += [two_part_sort(arry[i],arry[i+1])]
i +=2
if i == len(arry)-1:
result += [arry[i]]
return result
i =len(arry) +1
result = [[val] for _,val in enumerate(arry)]
while i >= 1:
result = binary_function(result)
i //= 2
return result[0]
Following is a typical iterative implementation of Merge Sort:
def mergeSorting3(self,arry):
def two_sorted_arrys_sorting_in_place(arry,left,mid,right):
result =[]
i,j = left,mid+1
while i <=mid and j <=right:
if arry[i] <= arry[j]:
result += [arry[i]]
i += 1
else:
result += [arry[j]]
j +=1
result += arry[i:mid+1]
result += arry[j:right+1]
arry[left:right+1] = result[0:right-left+1]
cur_size =1
while cur_size<len(arry) -1:
left =0
while left < len(arry) -1:
mid = left + cur_size-1
right = ((left+2*cur_size-1,len(arry)-1)[left+2*cur_size-1>len(arry)-1])
two_sorted_arrys_sorting_in_place(arry,left,mid,right)
left = left + cur_size*2
cur_size =2*cur_size