【算法】大规模排序

归并排序和快速排序都比较适合大规模的数据排序。两者都用到了分治的思想。

归并排序

归并排序的核心思想蛮简单的,如果要排序一个数组,我们先把数组从中间分成前后俩部分,然后对前后俩部分分别排序,再将排好序的俩部分合并再一起。这样一步一步往下分而治之,将整个排序分成小的子问题来解决。

由于这个是个递归,所以 找出终止条件如下:

merge_sort(p...r) = merge(merge_sort(p...middle),merge_sort(middle+1...r)

其中当p >= r时不用再继续分解,或者如果是middle = middle // 2时,当middle == 1 不用再继续分解。

这个递归公式的解释如下:

def merge(left:list,right:list)->list:
    temp = list()
    if left[-1] <= right[0]:
        temp = left + right
        return temp
    if right[-1] <= left[0]:
        temp = right +left
        return temp
    left_index = right_index = 0
    while left_index <len(left) and right_index <len(right):
        if left[left_index] < right[right_index]:
            temp.append(left[left_index])
            left_index += 1
        else:
            temp.append(right[right_index])
            right_index += 1
    if left_index  == len(left):
        temp += right[right_index:]
    else:
        temp += left[left_index:]
    return temp
def merge_sort(li:list)->list:
    if len(li) <= 1:
        return li
    middle = len(li)//2
    left = merge_sort(li[:middle])
    right = merge_sort(li[middle:])
    return merge(left,right)

猜你喜欢

转载自www.cnblogs.com/guangluwutu/p/11807366.html