【算法】大规模排序

☆樱花仙子☆ 提交于 2019-12-03 20:34:09

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

归并排序

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

 

 

 

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)

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!