python 经典排序方法(冒泡排序,快速排序,二分法查找)

时间:2020-11-28 22:13:51

闲来无事,回忆了一下刚开始学python的时候学的几个排序方法:

"""冒泡排序"""
num = [11, 3, 5, 6, -9, -8, -5, -66, 99, 88, 52]
for x in range(len(num)):
    for y in range(len(num)-x-1):
        if num[y] > num[y+1]:
            num[y], num[y+1] = num[y+1], num[y]
print(num)

for x in range(1, len(num)):
    for y in range(len(num)-x):
        if num[y] < num[y+1]:
            num[y], num[y+1] = num[y+1], num[y]
print(num)


"""快速排序"""
def quick_sort(lst):
    if len(lst)==1:
        return lst
    left = []
    right = []
    for x in range(1,len(lst)):
        if lst[0] > lst[x]:
            left.append(lst[x])
        elif lst[0] < lst[x]:
            right.append(lst[x])
        if len(left) > 1:
            left = quick_sort(left)
        elif len(right) > 1:
            right = quick_sort(right)
    return left+[lst[0]]+right


print(quick_sort(num))


# 二分法查找
def mid_search(lis,val):
    low = 0
    high = len(lis)-1
    while low <= high:
        mid = (low+high)//2
        if lis[mid] == val:
            return mid
        elif lis[mid] < val:
            low = mid+1
        else:
            high = mid-1
            
            
print(mid_search(range(0, 100000, 2), 35300))

嗯,还是原来的配方,还是熟悉的味道。。。。这些东西感觉好久都未用过了,,,,,,,,,,,,,,,,,,,,,,,,,