首页 > 技术文章 > 排序

knighterrant 2019-05-15 23:09 原文

li=[2,3,12,4,23,13,11]
# 冒泡排序
def bubble_sort(alist):

    n =len(alist)

    for j in range(n-1):

        count=0

        for i in range(n-1-j):

            if alist[i]>alist[i+1]:

                alist[i],alist[i+1] = alist[i+1],alist[i]

                count+=1

        if count==0:
            return

# 快排

def quit_sort(alist,first,last):

    # 递归的终止条件

    if first>=last:

        return

    #定义一个中间值

    mid_value = alist[first]

    #  两个游标
    low = first

    high = last
    #
    while low<high:

        while low < high and alist[low] < mid_value:
            # low一直向右走
            low += 1
            # 退出循环表示 alist[low]>mid_value
            # 把最大 值
        alist[high] = alist[low]

        while low<high and alist[high]>=mid_value:
            high-=1
        # 退出循环
        alist[low] = alist[high]


    # 将中间值放在中间位置

    alist[low] = mid_value

    quit_sort(alist,first,low-1)

    quit_sort(alist,low+1,last)


quit_sort(li,0,len(li)-1)

print(li)

#  二分查找
# 前提为有序列表
li=[1,2,3,5,6,78,90,341,547]

num=int(input("请输入一个数"))

def er_find(li,n):
    left = 0
    right = len(li) - 1
    while left<=right:
        mid=(left+right)//2
        if li[mid]>n:
            right=mid-1
        elif li[mid]<n:
            left=mid+1
        else:
            return True

    else:
        return False

print(er_find(li,num))

 

推荐阅读