算法

 1 lst=[1, 3, 5, 13, 43, 55, 55, 434, 464, 565, 665, 3341, 3433, 5646, 33434]
 2 count=0
 3 while count<len(lst):
 4     i=1
 5     while i <len(lst)-1:
 6         if lst[i]>lst[i+1]:
 7             lst[i],lst[i+1]=lst[i+1],lst[i]
 8         i+=1
 9     count+=1
10 print(lst)

冒泡  

 1 lst=[1, 3, 5, 13, 43, 55, 55, 434, 464, 565, 665, 3341, 3433, 5646, 33434]
 2 n=55
 3 left=0
 4 right=len(lst)-1
 5 count=1
 6 while left<=right:
 7     mid=(left+right)//2
 8     if n < lst[mid]:
 9         right = mid-1
10     if n > lst[mid]:
11         left = mid+1
12     else:
13         print(count)
14         print(mid)
15         break
16         count=count+1
17 else:
18     print("不在")

二分法查看是否在列表

 1 lst=[1,22,33,44,55,66,77,88,99,1112,5555]
 2 def func(n,left,right):
 3     if left<=right:
 4         mid=(left+right)//2
 5         if n<lst[mid]:
 6             right=mid-1
 7         elif n>lst[mid]:
 8             left=mid+1
 9         else:
10 
11             return mid
12         return func(n,left,right)#必须加,否则返回的是NONE
13     else:
14         return  -1
15 print(func(555,0,len(lst)-1))

 

posted @ 2018-08-15 21:10  逆欢  阅读(128)  评论(0编辑  收藏  举报