2.3二分搜索
def BinarySearch(my_list,x):
left =0
right = len(my_list)
while left<=right:
middle = (left+right)//2
if x==my_list[middle]:
return middle
elif x>my_list[middle]:
left = middle+1
else:
right = middle-1
return -1
2.7合并排序
def Merge(a,b):
c=[]
i = j =0
while i <len(a) and j < len(b):
if a[i]<b[j]:
c.append(a[i])
i+=1
else:
c.append(b[j])
j+=1
if i == len(a):
c +=b[j:]
else:
c +=a[i:]
return c
def MergeSort(my_list):
if len(my_list)<=1:
return my_list
middle = len(my_list)//2
left = MergeSort(my_list[:middle])
right = MergeSort(my_list[middle:])
return Merge(left,right)
if __name__ == '__main__':
a = [4, 7, 8, 3, 5, 9]
print(MergeSort(a))
2.8快速排序
def Partition(mylist,left,right):
i = left+1
j = right
x = mylist[left]
while True:
while mylist[i]<=x and i<right:
i+=1
while mylist[j]>x and j>left:
j-=1
if i>=j:
break
mylist[i],mylist[j] = mylist[j],mylist[i]
mylist[left] = mylist[j]
mylist[j] = x
return j
def QuickSort(mylist,left,right):
if left < right:
q = Partition(mylist,left,right)
QuickSort(mylist,left,q-1)
QuickSort(mylist,q+1,right)
if __name__ == '__main__':
a = [1,3,56,1,8,2,1,9,4]
print(QuickSort(a,0,len(a)-1))
print(a)
|