---- sorting algorithm merge sort

Merge sort

  Merge sort using the principle of divide and conquer:

    - two sequences into one sequence from a neutral position;

    - In the first step of the two sequences in accordance with half going to continue;

    - until the length of all sub-sequences are both 1, then two points is not turned off. This time again twenty-two ordered sequence can be merged into one.  

 

The third line in the figure represents the reciprocal of the data after the first consolidation. Wherein a set of data 48, 57. The two sets of data were combined way: each group of data specified in a pointer to the first element of each group of data, ordered for the offset specified by the data pointer. It is arranged as follows:

      1. p1 4 points, 5 points p2, p2 point P1 and the elements 4 and 5 merge comparison, the smaller data to a new list. By comparison p1 4 points will be added to the new list, the p1 shifted back one, pointing to the 8, p2 unchanged.

      And elements 8,5 p2 point to continued relatively 2.p1, then p2 points to 5 small, added to the new list, p2 shifted back one, pointing to seven.

      And elements p2 point to continued relatively 3.p1 8,7, 7 added to the new list, p2 offset points to NULL, the comparison ends.

      4. A pointer to the last remaining data (which contains pointers to all data following the data) directly to the new list to.

  

  

 1 def merge_sort(alist):
 2     n = len(alist)
 3     #结束递归的条件
 4     if n <= 1:
 5         return alist
 6     #中间索引
 7     mid = n//2
 8 
 9     left_li = merge_sort(alist[:mid])
10     right_li = merge_sort(alist[mid:])
11 
12     #指向左右表中第一个元素的指针
13     left_pointer,right_pointer = 0,0
14     #合并数据对应的列表:该表中存储的为排序后的数据
15     result = []
16     while left_pointer < len(left_li) and right_pointer < len(right_li):
17         #比较最小集合中的元素,将最小元素添加到result列表中
18         if left_li[left_pointer] < right_li[right_pointer]:
19             result.append(left_li[left_pointer])
20             left_pointer += 1
21         else:
22             result.append(right_li[right_pointer])
23             right_pointer += 1
24     #当左右表的某一个表的指针偏移到末尾的时候,比较大小结束,将另一张表中的数据(有序)添加到result中
25     result += left_li[left_pointer:]
26     result += right_li[right_pointer:]
27 
28     return result
29 
30 alist = [3,8,5,7,6]
31 print(merge_sort(alist))

 

Guess you like

Origin www.cnblogs.com/open-yang/p/11367103.html