列表排序之LOW_B三人组

LOW_B三人组

时间复杂度:O(n**2)
空间复杂度:O(1),原地排序,没有开新列表

冒泡排序(重点)

1、每走一趟,最大的数会顶上去;
2、有序区增加,无序区减少一个数;
3、前一个数若比后一个数小,则调换位置。

# 计时装饰器
def cal_time(func):
    def wrapper(*args, **kwargs):
        import time
        t1 = time.time()
        result = func(*args, **kwargs)
        t2 = time.time()
        print("%s running time: %s secs." % (func.__name__, t2-t1))
        return result
    return wrapper
    
    
l = list(range(10000))
import random
random.shuffle(l)

@cal_time
def bubble_sort(lst):
    for i in range(len(l)-1):  # 趟数,三个数两趟
        exchange=False
        for j in range(len(l)-i-1):
            # 从i=0开始,将最大数换到最右侧,走完一趟,则排序区域缩减一次
            if l[j] > l[j + 1]:
                l[j], l[j + 1] = l[j + 1], l[j]
            exchange=False
        if not exchange:
            return 
        
    return lst

lst = bubble_sort(l)  
# bubble_sort running time: 21.856462240219116 secs.

改进版:若一次都没有交互,则说明本身就是有序的,无序排序

@cal_time
def bubble_sort(lst):
    exchage = False
    for i in range(len(l)-1):  # 趟数,三个数两趟
        for j in range(len(l)-i-1):
            # 从i=0开始,将最大数换到最右侧,走完一趟,则排序区域缩减一次
            if l[j] > l[j + 1]:
                l[j], l[j + 1] = l[j + 1], l[j]
                exchage = True
        if not exchage:
            return
    return lst

# 传入有序列表

# 改进后 bubble_sort running time: 0.002501249313354492 secs.

# 改进前  bubble_sort running time: 12.09149432182312 secs. 

选择排序

1、一趟遍历完记录最小的数,放到第一个位置;
2、再在一趟遍历记录剩余列表中的最小的数,继续放置。

# 选择排序

@cal_time
def choice(list):
    """选择排序,将最小数放在第一位,每次都会缩小排序区域"""
    for i in range(0,len(list)):
        min_loc = i  # 从索引0开始取参考值

        # 将剩余区域内的数逐个与min_loc的数比较,
        # 若比min_loc对应的值小则取代之,最后会取到此趟最小值索引
        for j in range(i+1,len(list)):
            if list[j] < list[min_loc]:
                min_loc = j
        # 到最后就确定了这一趟的最小值的索引位置

        list[i],list[min_loc] = list[min_loc],list[i]
        # 位置对调,将当前排序区域的最小数与第一个数对调

    return list
    
# choice running time: 9.044977188110352 secs.

插入排序

手里的牌(有序区域),每次从无序区域摸到牌插入到有序区域。

lst = [5, 4, 3, 7, 8, 6, 2, 0, 4, 9]
#  第一个数默认为有序区域,即为5,之后区域默认为无序区域


@cal_time
def insert_sort(lst):
    for i in range(1, len(lst)):  # i指摸到的牌索引,排除第一张牌
        temp = lst[i]  # 取无序区第一张
        j = i - 1  # 取有序区最后一张
        while lst[j] > temp and j >= 0:
            # 和手里的牌比较,若比手里的牌小则手里的牌右移
            # 此时不会打乱列表索引,因为覆盖的只是要比较的那一张牌
            lst[j + 1] = lst[j]
            j = j - 1
        lst[j + 1] = temp

    return lst

猜你喜欢

转载自www.cnblogs.com/fqh202/p/9375451.html
今日推荐