算法学习ing,自己做个记录

#二分查找
def erfen(list,a):
    i=0
    low=0
    high=len(list)-1
    while low<=high:
        mid=(low+high)/2
        guess=list[mid]
        if guess==a:
            i+=1
            return guess,i
        if guess>a:
            i+=1
            high=mid-1
        else:
            i+=1
            low=mid+1
    return None
xx=[]
for i in range(100):
    xx.append(i)
a,i=erfen(xx,40)
print a,i
#选择排序
def findsmallest(arr):
    smallest=arr[0]
    smallest_index=0
    for i in range(1,len(arr)):
        if arr[i]<smallest:
            smallest=arr[i]
            smallest_index=i
    return smallest_index
#选择排序
def selectionsort(arr):
    newarr=[]
    for i in range(len(arr)):
        smallest=findsmallest(arr)
        newarr.append(arr.pop(smallest))
    return newarr
a=[12,3,4,23523,234,234,23423,4]
x=selectionsort(a)
print(x)
#计算阶乘
def fact(x):
    if x==1:
        return x
    else:
        return x*fact(x-1)
print(fact(5))

下面是递归

#递归
def sum1(x):
    if x==[]:
        return 0
    return x[0]+sum1(x[1:])
print(sum1([1,2,3,4,5,6,7]))

def avg1(x):
    if x==[]:
        return 0
    return 1+avg1(x[1:])
print(avg1([1,2,3]))

def max1(x):
    if len(x)==2:
        return x[0] if x[0]>x[1] else x[1]
    sub_max=max1(x[1:])
    return x[0] if x[0]>sub_max else sub_max
print(max1([1,2,3,4]))

快速排序

def quicksort(array):
    if len(array)<2:
        return array
    else:
        pivot=array[0]
        less=[i for i in array[1:] if i<=pivot]
        greater=[i for i in array[1:] if i > pivot]
        return quicksort(less)+[pivot]+quicksort(greater)
print(quicksort([10,5,2,4,3]))

记录以防忘记

点赞