Data structures and algorithms - sorting algorithm - merge sort

 ################## merge sort #######################

"" " 
Merge algorithm logic 

split 
for splitting the entire sequence, a portion of the left, right part 
and each part is split again, until there is only one element to split, at its worst, 
1st Split: 54, 26, 93, 17, 77, 31, 44, 55, 
2nd split: 54, 26, 93, 17, 77, 31, 44, 55, 
the third split: 54, 26, 93, 17, 77, 31, 44, 55, 
4th resolution: 54, 26, 93, 17, 77, 31, 44, 55, 

merge 
and then split again to merge small front, after a large, 
1st combined: 26, 54, 17,93 31,77, 44, 55, 
the second merger, it needs two cursors, left, right, 
26, 54, 17,93 
on the left point to initial cursor 26, cursor to the right initial point 17, 
then the first left and right turn comparison, if the left panel, a digital still and then moves the cursor to the right of the back, if the right panel, the left and right digital switching put, 
and then left the first comparison End one, then the second is to know the numbers are small to large order, 
the third way of merger are the same, until all are sorted, 

code implementation, 
or the need to use Return, 

"" "

 

################## merge sort #######################

merge_sort DEF (alist): 
    n-= len (alist) 
    IF n-<=. 1: # This is not split if only one element down, and this is the end of the recursive conditions 
        return alist 
    MID = n-2 // 
    # What is left portion 
    left = merge_sort (alist [: MID]) 
    # this is the section to the right, 
    right = merge_sort (alist [MID:]) 
    # combined: 
    # merge (left, right) 

    # define two cursors 
    left_pointer, right_pointer = 0, 0 
    Result = [] 

    the while left_pointer <len (left) and right_pointer <len (right): 
        IF left [left_pointer] <right [right_pointer]: 
            result.append (left [left_pointer]) 
            left_pointer + =. 1 
        the else: 
    Result + = left [left_pointer:] 
            result.append (right [right_pointer])
            + =. 1 right_pointer
    + = right Result [right_pointer:] 
    return Result 


IF the __name__ == '__main__': 
    alist = [54,26,93,17,77,31,44,55,20] 
    Print (alist) 
    sorted_alist = merge_sort (alist) 
    Print (sorted_alist) 

# this sort is over, following about search,

 

Guess you like

Origin www.cnblogs.com/andy0816/p/12348382.html