zoukankan      html  css  js  c++  java
  • 数据结构学习(shell排序和归并排序)

    # coding=utf-8
    
    
    # shell排序
    # 参数alist:被被排序的列表
    def shellsort(alist):
    
        gap = len(alist) / 2
    
        while gap > 0:
    
            for i in range(gap):
                shellinsert(alist, i, gap)
    
            gap = gap / 2
    
            print alist
    
    #根据步长进行插入排序
    def shellinsert(alist, start, gap):
    
        for i in range(start + gap, len(alist), gap):
            temp = alist[i]
            position = i
    
            while position >= gap and alist[position - gap] > temp:
                alist[position] = alist[position - gap]
                position = position - gap
            alist[position] = temp
    
    
    # 归并排序
    # 参数alist:被被排序的列表
    def mege_sort(alist):
        if len(alist) <= 1:
            return alist
    
        num = int(len(alist) / 2)
    
        leftList = mege_sort(alist[:num])
        rightList = mege_sort(alist[num:])
    
        return mege(leftList, rightList)
    
    #将两个列表合并为一个列表进行返回
    def mege(leftList, rightList):
        l = 0
        r = 0
    
        result = []
    
        while l < len(leftList) and r < len(rightList):
            if leftList[l] < rightList[r]:
                result.append(leftList[l])
                l += 1
            else:
                result.append(rightList[r])
                r += 1
    
        result = result + leftList[l:]
        result = result + rightList[r:]
    
        return result
    
    alist = [9, 8, 9, 9, 7, 6, 5, 4, 3, 2, 1]
    
    if __name__ == '__main__':
        # shellsort(alist)
    
        result = mege_sort(alist)
    
        print alist
        print result
    

      

  • 相关阅读:
    Iscroll滑动无效
    原生js 无缝滚动组件
    原生 js dialog弹窗组件
    html5 历史管理
    html5拖拽属性
    highcharts 数据图设置X轴间隔显示效果
    highcharts柱状图含有正负柱设置不同颜色的方法
    移动端滑动插件 swiper
    千分位添加和去掉方法
    dubbo常用类和路径
  • 原文地址:https://www.cnblogs.com/qingtianyu2015/p/6033824.html
Copyright © 2011-2022 走看看