【Python】【算法】【排序】用Python实现排序的三种算法

class SortTest:

    def __init__(self):
        pass

    # 冒泡排序
    def BubbleSort(self, value):
        if isinstance(value, list):
            print("This is a list")
            for i in range(len(value)):
                for j in range(i + 1, len(value)):
                    if value[i] > value[j]:
                        tmp = value[j]
                        value[j] = value[i]
                        value[i] = tmp
            print(value)
        else:
            print("This isn't list!")

    def ZenofPythonBubbleSort(self, value):
        if isinstance(value, list):
            for i in range(len(value)):
                for j in range(i + 1, len(value)):
                    if value[i] > value[j]:
                        value[i], value[j] = value[j], value[i]
            print(value)
        else:
            print("This isn't list!")

    # 选择排序
    def ChoiceSort(self, value):
        if isinstance(value, list):
            # 就是找最小/最大数的下标

            for i in range(len(value)):
                index = i
                for j in range(i, len(value)):
                    if value[index] > value[j]:
                        index = j
                value[i], value[index] = value[index], value[i]
            print(value)
        else:
            print("This isn't list!")

    # 插入排序
    def InsertSort(self, value):
        if isinstance(value, list):
            # 从未排过序的数中找到最大/最小的那个比较后插入到前排
            for i in range(1, len(value)):
                j = i - 1
                if value[i] < value[j]:
                    temp = value[i]
                    value[i] = value[j]

                    j = j - 1
                    while j >= 0 and value[j] > temp:
                        value[j + 1] = value[j]
                        j = j - 1

                    value[j + 1] = temp

            print(value)

    def InsertSort2(self, value):
        if isinstance(value, list):
            for i in range(1, len(value)):
                j = i - 1
                if value[i] < value[j]:
                    temp = value[i]
                    value[i] = value[j]

                    j = j - 1
                    while j >= 0 and value[j] > temp:
                        value[j + 1] = value[j]
                        j = j - 1
                    value[j + 1] = temp

        else:
            print("This isn't list!")


if __name__ == '__main__':
    st = SortTest()
    test = [9, 8, 6, 5, 4, 3, 2, 1]
    value = [1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1]
    # st.ZenofPythonBubbleSort(test)
    # st.ChoiceSort(test)
    st.InsertSort(test)

 

posted @ 2019-05-16 22:08  石砾  阅读(284)  评论(0编辑  收藏  举报