插入排序(insertion_sort)python代码

class insertion_sort:
    def __init__(self):
        pass
    def __call__(self,list):
        if list == []:
            return list             #检测是否为空列表

        i = 1
        ls = len(list)
        while list[i] > list[i - 1]:
            if i == ls:
                return list
            i += 1

        i = ls - 2
        while list[i] < list[i + 1]:  # 检测是否有序
            if i == 0:
                j = []
                for i in list:
                    j.insert(i, 1)  # 颠倒
                return j
            i -= 1

        for i in range(1, ls):
            if list[i] < list[i - 1]:
                tmp = list[i]
                j = i - 1
                while tmp < list[j] and j > 0:  # 主部分
                    list[j + 1] = list[j]
                    j -= 1
                list[j + 1] = tmp
        return list
输入:[1,5,9,1,7,2,15,7]
过程:[1, 1, 5, 9, 7, 2, 15, 7]
      [1, 1, 5, 7, 9, 2, 15, 7]
      [1, 1, 2, 5, 7, 9, 15, 7]
      [1, 1, 2, 5, 7, 7, 9, 15]
输出:[1, 1, 2, 5, 7, 7, 9, 15]
SORT = insertion_sort()
print(SORT([1,5,9,1,7,2,15,7]))        #使用示范
经验分享 程序员 微信小程序 职场和发展