首页 > 编程语言 > 详细

使用Python完成排序(快排法、归并法)

时间:2019-04-08 18:46:58      阅读:176      评论:0      收藏:0      [点我收藏+]
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[:]))

使用Python完成排序(快排法、归并法)

原文:https://www.cnblogs.com/lyg-blog/p/10672404.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!