常用排序算法(python实现)

前段时间把主要的排序算法原理看了一遍,光看不行,还是得动手。

排序算法 python (Sort.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!--
#ChooseSort


class Sort(list):
    def __init__(self, list):
        self.list = list

    def swap(self, i, j):
        list[i], list[j] = list[j], list[i]

    def show(self):
        print " ".join(str(v) for v in list)

    def select_sort(self):
        for i in range(0, len(list)-1):
            min = i
            for j in range(i+1, len(list)):
                if list[j] < list[min]:
                    min = j
            self.swap(min, i)
        return list

    def insert_sort(self):
        for i in range(1, len(list)):
            temp = list[i]
            j = i-1
            while j >= 0 and temp < list[j]:
                list[j+1] = list[j]
                j -= 1
            list[j+1] = temp

    def quick_sort(self, low=0, high=None):
        if high == None:
            high = len(list) - 1
        if low < high:
            s, i, j = list[low], low, high
            while True:
                while i != high and list[i] < s:
                    i = i + 1
                # if i < j:
                #     list[i] = list[j]
                #     i = i + 1
                while j !=low and list[j] > s:
                    j = j - 1
                # if i < j:
                #     list[j] = list[i]
                #     j = j - 1
                if i < j:
                    list[j], list[i] = list[i], list[j]
                else:
                    break
            list[j], s = s, list[j]
            self.quick_sort(low, i - 1)
            self.quick_sort(i + 1, high)

    def bubble_sort(self):
        for i in range(len(list) - 1, 0, -1):
            for j in range(0, i):
                if list[j] > list[j + 1]:
                    list[j], list[j + 1] = list[j + 1], list[j]


if __name__ == "__main__":
    list = [6, 4, 1, 9, 2, 7, 10, 3]
    print 'select_sort'
    s = Sort(list)
    s.select_sort()
    s.show()

    list = [6, 4, 1, 9, 2, 7, 10, 3]
    print 'insert_sort'
    s = Sort(list)
    s.insert_sort()
    s.show()

    list = [6, 4, 1, 9, 2, 7, 10, 3]
    print 'quick_sort'
    s = Sort(list)
    s.quick_sort(0, len(list)-1)
    s.show()

    list = [6, 4, 1, 9, 2, 7, 10, 3]
    print 'bubble_sort'
    s = Sort(list)
    s.bubble_sort()
    s.show()