zoukankan      html  css  js  c++  java
  • 使用Python完成排序(快排法、归并法)

    class Sort(object):
        def quick_sort(self, ls):
            self.quick_sort_helper(ls, 0, len(ls) - 1)
            return ls
    
        def quick_sort_helper(self, ls, start, end):
            if end <= start:
                return
            pivot_index = random.randint(start, end)
            pivot = ls[pivot_index]  # pivot value
            ls[pivot_index], ls[end] = ls[end], ls[pivot_index]  # swap with the value in index end.
            boundary = start  # boundary is in index start.
            for i in range(start, end):
                if ls[i] < pivot:
                    ls[i], ls[boundary] = ls[boundary], ls[i]  # swap with the value in index i.
                    boundary += 1
            ls[boundary], ls[end] = ls[end], ls[boundary]  # lie the pivot in index boundary.
            self.quick_sort_helper(ls, start, boundary - 1)
            self.quick_sort_helper(ls, boundary + 1, end)
    
        def merge_sort(self, ls):
            buffer = ls[:]
            self.merge_sort_helper(ls, buffer, 0, len(ls) - 1)
            return ls
    
        def merge_sort_helper(self, ls, buffer, start, end):
            if end <= start:
                return
            middle = (start + end) // 2
            self.merge_sort_helper(ls, buffer, start, middle)
            self.merge_sort_helper(ls, buffer, middle + 1, end)
            i1, i2 = start, middle + 1
            for i in range(start, end+1):
                if i2 > end:
                    buffer[i] = ls[i1]
                    i1 += 1
                elif i1 > middle:
                    buffer[i] = ls[i2]
                    i2 += 1
                elif ls[i1] < ls[i2]:
                    buffer[i] = ls[i1]
                    i1 += 1
                else:
                    buffer[i] = ls[i2]
                    i2 += 1
            ls[start:end+1] = buffer[start:end+1]
    
    if __name__ == '__main__':
        ls = [1, 9, 5, 4, 3, 7, 6]
        s = Sort()
        print(s.quick_sort(ls[:]))
        print(s.merge_sort(ls[:]))
    
  • 相关阅读:
    读《被绑架的中国经济》有感
    互联网世界观
    了解360 ~~《我的互联网方法论》
    了解腾讯~~《马化腾的商业帝国》
    nginx 动静分离 以及 负载均衡配置
    linux 常用命令
    solr 配置中文分词器
    solr搜索配置权重
    JDK8集合类源码解析
    JDK8集合类源码解析
  • 原文地址:https://www.cnblogs.com/lyg-blog/p/10672404.html
Copyright © 2011-2022 走看看