Data structure algorithm--5 merge sort

merge sort

Let’s first look at how merge sort works

 Two ordered lists, the low pointer points to 2, the high pointer points to 6, and the mid pointer points to 9.

Create a new list, 1<2, so 1 is put into the list, the right pointer is moved one position to the right, then 2 and 3 are compared, 2 is put into the list, the left pointer is moved one position to the right, and so on. There must be some parts of the list that are not there first. number, then directly append another list into the new list.

def merge(li,low,mid,high):
    i=low
    j=mid+1
    ltmp=[]
    while i<=mid and j<=high: # 只要两边都有数
        if li[i]<li[j]:
            ltmp.append(li[i])
            i+=1
        else:
            ltmp.append(li[j])
            j+=1
    # 执行完上个while,肯定有一部分没数了
    while i<=mid:
        ltmp.append(li[i])
        i+=1
    while j<=high:
        ltmp.append(li[j])
        j+=1
    li[low:high+1]=ltmp

For an array, we merge and sort it:

>Decompose: Divide the list into smaller and smaller pieces until it is divided into one element.

> Termination condition: One element is ordered.

>Merge: Talk about merging two ordered lists, and the lists will become larger and larger.

We can see that recursive thinking is used to complete the code

def merge_sort(li,low,high):   # 这里递归就是左右,最后左右一起
    if low<high:  # 至少有两个元素,递归
        mid=(low+high)//2
        merge_sort(li,low,mid)   # 等其递归完成返回一个左侧有序列表
        merge_sort(li,mid+1,high) # 等其递归完返回一个右侧有序列表
        merge(li,low,mid,high)   # 将两个合并

li=list(range(10))
random.shuffle(li)
print(li)
merge_sort(li,0,len(li)-1)
print(li)

If you feel unclear about this process, we can change the last step of the recursion, merge(li, low, mid, high), to print.

[4, 7, 2, 8, 10, 13, 12, 6, 1, 11, 3, 5, 9, 0, 14, 15]
[4, 7]
[2, 8]
[4, 7, 2, 8]
[10, 13]
[12, 6]
[10, 13, 12, 6]
[4, 7, 2, 8, 10, 13, 12, 6]
[1, 11]
[3, 5]
[1, 11, 3, 5]
[9, 0]
[14, 15]
[9, 0, 14, 15]
[1, 11, 3, 5, 9, 0, 14, 15]
[4, 7, 2, 8, 10, 13, 12, 6, 1, 11, 3, 5, 9, 0, 14, 15]

We can see that recursive sorting is performed from small to large, and from left to right

And the time complexity of merge sort is O(nlogn) and the space complexity is O(n)

Comparison of quick sort, merge, and heap sort:

In general: quick sort < merge sort < heap sort

Disadvantages of the three sorting methods:

Quick sort: Sorting efficiency is low in extreme cases

Merge sort: requires additional memory overhead

Heap sort: relatively slow among fast sorting algorithms

 

Guess you like

Origin blog.csdn.net/qq_64685283/article/details/132520281