常用算法

冒泡排序

"""
### 时间复杂度:即程序运行的大概次数
#该时间复杂度 O(n^2)

def bubble_sort(li):
    for i in range(len(li)-1):   # 趟的次数,最后一趟就不用走了

        flag = True
        for j in range(len(li)-1-i):  # 最后一个数不用比较,以及已经走了多少趟
            if li[j] > li[j+1]:
                li[j], li[j+1] = li[j+1], li[j]
                flag = False

        if flag:
            return

li = [7, 5, 4, 6, 3, 8, 2, 9, 1]
bubble_sort(li)
print(li)
"""

选择排序

"""
### 选择排序
# 时间复杂度:O(n^2)
def select_sort(li):
    for i in range(len(li)):
        minloc = i  # 假设默认第一个是最小的
        for j in range(i+1, len(li)):
            if li[minloc] > li[j]:
                li[minloc], li[j] = li[j], li[minloc]

li = [7, 5, 4, 6, 3, 8, 2, 9, 1]
select_sort(li)
print(li)
"""

插入排序

"""
### 插入排序
# 时间复杂度:O(n^2)
def insert_sort(li):

    for i in range(1, len(li)):
        temp = li[i]  # i = 2  temp=li[2]=4
        j = i - 1  # j = 1

        while j >= 0 and li[j] > temp:
            li[j+1] = li[j] #[[5,7,7,6,3,8,2,9,1]] ==> [5,5,7,6,3,8,2,9,1]
            j = j - 1 # j = 0

        li[j+1] = temp
        
li = [7, 5, 4, 6, 3, 8, 2, 9, 1]
insert_sort(li)
print(li)
"""

快排

"""
#### 快排
# 时间复杂度是:O(nlogn)
def partition(li, left, right):  # O(n)

    temp = li[left]

    while left < right:
        while left < right and li[right] >= temp:
            right = right - 1
        li[left] = li[right]  # 将大于小于归为中间数扔到前面去

        while left < right and li[left] <= temp:
            left = left + 1
        li[right] = li[left]

    li[left] = temp

    return left  # 把中间位置的返回出去


def quick_sort(li, left, right):
    if left < right:
        mid = partition(li, left, right)  # 归为函数

        quick_sort(li, left, mid-1)   # O(logn)
        quick_sort(li, mid+1, right)
        
li = [7, 5, 4, 6, 3, 8, 2, 9, 1]
quick_sort(li, 0, len(li)-1)
print(li)
"""
posted @ 2020-04-02 17:20  alen_zhan  阅读(113)  评论(0编辑  收藏  举报
返回顶部