#!/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))
排序
最新推荐文章于 2024-03-28 00:29:10 发布