Good programmers to learn Python route SHARE merge sort algorithm

Python implementation merge sort algorithm


Merge sort first proposed in 1945 by John von Neumann. The algorithm is very typical application uses a divide and conquer (Divide and Conquer), and the layers can be simultaneously performed recursively partition.


The basic idea of ​​divide and conquer


The original problem is decomposed into a number of smaller-scale but similar structure to the original question of sub-problems. Solutions of these sub-problems recursively, and then these solutions for the combination of sub-problem solution of the original problem.


The basic idea of ​​the sort of merge


A sorted array, we first array is divided into front and rear portions from the middle, and front and rear portions are sorted, and then two rows of the ordered part are combined, so that the entire array are ordered on the.


Animation


(Please insert ms.webp this picture in the published articles)


Code


```python

def merge(left, right):

'' 'Merging and sorting' ''

i = 0

j = 0

result = []

length_left = len(left)

length_right = len(right)

while i < length_left and j < length_right:

#-By-element comparison of the two lists

# Add a new list of small, relatively large stay on

if left[i] <= right[j]:

result.append(left[i])

i += 1

else:

result.append(right[j])

j += 1

# Finally add elements that are not comparable

result.extend(left[i:])

result.extend(right[j:])

return result

def merge_sort(lists):

'' 'Merge sort inlet split list' ''

# Recursive conditional exit

length = len(lists)

if length <= 1:

return lists

# Recursive partitioning, rounding, compatible py3

mid = length // 2

left = merge_sort(lists[:mid])

right = merge_sort(lists[mid:])

# Merge sort (merge sort)

return merge(left, right)


numbers = [4, 0, 7, 9, 2, 8, 1, 3, 6, 5]

assert merge_sort(numbers) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

```




Guess you like

Origin blog.51cto.com/14479068/2436878