栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python数据结构———合并排序

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python数据结构———合并排序

合并排序
    合并排序:通过将数据分为n个组,通过n步分别排序并合并;是一个稳定的排序算法;通过比较 log2^n 次处理;时间复杂度:O(n*log2^n);额外空间:O(n);
代码
list1 = [20, 45, 51, 88, 99999]
list2 = [98, 10, 23, 15, 99999]
list3 = []


def merge_sort():
    global list1
    global list2
    global list3

    select_sort(list1, len(list1) - 1)
    select_sort(list2, len(list2) - 2)

    My_Merge(len(list1) - 1, len(list2) - 1)


def select_sort(data, size):
    for base in range(size - 1):
        small = base
        for j in range(base + 1, size):
            if data[j] < data[small]:
                small = j
        data[small], data[base] = data[base], data[small]


def My_Merge(size1, size2):
    global list1
    global list2
    global list3

    index1 = 0
    index2 = 0
    for index3 in range(len(list1) + len(list2) - 2):
        if list1[index1] < list2[index2]:
            list3.append(list1[index1])
            index1 += 1
        else:
            list3.append(list2[index2])
            index2 += 1


if __name__ == '__main__':
    merge_sort()
    print(list1)
    print(list2)
    print(list3)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/739639.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号