python实现快排算法

前面我们讲了快排算法,现在我们来用代码实现一下

#!/usr/bin/python
# -*- coding: utf-8 -*-
#快速排序

def quick_sort(the_list, start, end):
    if start < end:
        m, n = start, end
        base = the_list[m]
        while m < n:
            while (m < n) and (the_list[n] >= base):
                n = n-1
            the_list[m]=the_list[n]
            while (m < n) and (the_list[m] <= base):
                m = m+1
            the_list[n] = the_list[m]
        the_list[m] = base
        quick_sort(the_list, start, m-1)
        quick_sort(the_list, n+1, end)
    return the_list

if __name__ == '__main__':
    the_list = [10,1,18,30,23,12,7,5,18,17]
    start = 0
    end = len(the_list) - 1
    print the_list
    print quick_sort(the_list, start, end)

结果如下

[10, 1, 18, 30, 23, 12, 7, 5, 18, 17]
[1, 5, 7, 10, 12, 17, 18, 18, 23, 30]

猜你喜欢

转载自blog.csdn.net/stronglyh/article/details/82155877