zoukankan      html  css  js  c++  java
  • 使用PYTHON完成排序(堆排序)

    class HeapStructure:
        def __init__(self, ls):
            self.ls = ls
    
        def shift_up(self, index):  # 上移使符合堆要求
            if index == 0:
                return
            ls = self.ls
            par_index = (index - 1) // 2
            if ls[par_index] < ls[index]:
                ls[par_index], ls[index] = ls[index], ls[par_index]
            self.shift_up(index-1)
    
        def shift_down(self, index, last_index):  # 下移使符合堆要求
            ls = self.ls
            child_left, child_right = 2 * index + 1, 2 * index + 2
            if child_left > last_index:
                return
            if child_left < last_index and ls[child_left] < ls[child_right]:
                if ls[index] < ls[child_right]:  # 与右子节点交换
                    ls[index], ls[child_right] = ls[child_right], ls[index]
                    self.shift_down(child_right, last_index)
            else:
                if ls[index] < ls[child_left]:  # 与左子节点交换
                    ls[index], ls[child_left] = ls[child_left], ls[index]
                    self.shift_down(child_left, last_index)
    
        def sort(self):
            i = len(self.ls)
            if i == 0:
                return self.ls
            last_index = i - 1
            self.shift_up(last_index) # 变为最大堆
            self.ls[0], self.ls[last_index] = self.ls[last_index], self.ls[0] # 最大值移动到队尾
            last_index -= 1
            while last_index:
                self.shift_down(0, last_index=last_index) # 调整为最大堆
                self.ls[0], self.ls[last_index] = self.ls[last_index], self.ls[0]
                last_index -= 1
            return self.ls
    
    
    if __name__ == '__main__':
        ls = [5, 1, 2, 4, 8, 0, 9]
        print(HeapStructure(ls).sort())
        ls = []
        print(HeapStructure(ls).sort())
    
  • 相关阅读:
    拖拽改变元素位置或大小bug修复
    拖拽改变元素位置或大小
    vue使用input上传多张图片,可以预览
    javaScript面向对象编程学习(二)
    移动端适配字体大小
    js的时间戳的转换
    vue-cli3.X中的vue.config.js的配置
    javaScript面向对象编程学习(一)
    Visual Studio code 常用插件集集合。
    js的四个小练习
  • 原文地址:https://www.cnblogs.com/lyg-blog/p/10700762.html
Copyright © 2011-2022 走看看