# 二分查找的递归与非递归方式

'''

# 非递归方式二分法查找

def binsearch(list2,num):
paixu(list2)# 进行二分查找一定是对于有序数组
print(list2)
leng = len(list2)# 求计算的列表长度
start = 0
end = leng-1
while start <= end:
mid = (start+end) // 2
print('mid%d'%mid)
if num < list2[mid]:
end = mid-1
elif num > list2[mid]:
start = mid+1
else:
return mid
return -1

def paixu(list1):
leng = len(list1)
for i in range(leng):
for j in range(i, leng - i - 1):
if list1[j] > list1[j + 1]:
list1[j], list1[j + 1] = list1[j + 1], list1[j]
return list1

list1 = [12,34,65,23,54,65,78,25,90]
print(binsearch(list1,54))#排序后的索引

'''

# 递归解决二分法查找
def paixu(list1):
leng = len(list1)
for i in range(leng):
for j in range(i, leng - i - 1):
if list1[j] > list1[j + 1]:
list1[j], list1[j + 1] = list1[j + 1], list1[j]
return list1

def bin_search(list1,left,right,num):
paixu(list1)
if left > right:
return -1
mid = (right+left) // 2
print('mid=%d'%mid)
if list1[mid] == num:
return mid
elif list1[mid] > num:
bin_search(list1,left,right-mid,num)
else:
bin_search(list,left-mid,right,num)

list1 = [12,34,65,23,54,65,78,25,90]
leng = len(list1)
print(bin_search(list1,0,leng-1,54))#排序后的索引

12-26

10-17 17
01-06 525
06-13 2778
04-27 13万+
06-17
08-30
08-06 5万+
01-17 450
09-05
05-25 9215
09-06 692
03-19 202
02-09 2146
11-06 1286
04-01 455
07-20 594