排序

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
冒泡排序(会背)
"""
count = 0
list1 = [9, 1, 7, 3, 2, 4, 6]
for j in range(len(list1)-1, 0, -1):
    print(f"这是第{len(list1)-j}轮排序开始")
    for i in range(j):
        if list1[i] > list1[i+1]:
            list1[i], list1[i+1] = list1[i+1], list1[i]
            count += 1
    print(f"这是第{len(list1)-j}轮排序结束")
print(f"总共交换{count}次")
print(list1)

print('************')


"""
选择排序
"""

list2 = [4, 6, 3, 8, 34, 89, 80]
for i in range(len(list2)):
    min_index = i
    for j in range(i+1, len(list2)):
        if list2[min_index] > list2[j]:
            min_index = j
    if min_index != i:
        list2[i], list2[min_index] = list2[min_index], list2[i]
        count += 1
print(count)
print(list2)

print('************')

"""
list3 = [
    [1, 2, 3],
    [4, 5, 6],
    [5, 10, 12]
]

def search(list3, value):
    for list4 in list3:
         if value in list4:
            print('找到了')
            return True
    return False

print(search(list3, 7))

"""

"""
插入排序
"""

a = [2, 4, 5, 8, 7, 0, 40]
num = 0
for i in range(1, len(a)):
    for j in range(i, 0, -1):
        if a[j] < a[j-1]:
            a[j], a[j-1] = a[j-1], a[j]
            num += 1
print(num)
print('=======', a)

"""
二分法递归查找
"""


def binary_search(alist, item):
    if len(alist) == 0:
        return False
    else:
        midpoint = len(alist)//2
        if alist[midpoint] == item:
            return True
        else:
            if item < alist[midpoint]:
                return binary_search(alist[:midpoint], item)
            else:
                return binary_search(alist[midpoint+1:], item)


testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(binary_search(testlist, 3))
print(binary_search(testlist, 13))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值