冒泡排序
def bubbleSort(a):
for i in range(len(a)-1):
flag=True
for j in range(len(a)-1-i):
if a[j]>a[j+1]:
a[j],a[j+1]=a[j+1],a[j]
flag=False
if flag:
break
print(a)#打印排序过程
def main():
a=[865,451,239,12,192,180,7,123,44,100]
bubbleSort(a)
print("-------------------------------------------------")
print("最终排序结果:")
print(a)
if __name__ == '__main__':
main()
选择排序
def selectionSort(a):
for i in range(0,len(a)):#外循环0~N-1
m=i#当前位置下标
for j in range(i+1,len(a)):#内循环
if a[j]<a[m]:
m=j
a[i],a[m]=a[m],a[i]
def main():
a=[59,12,77,64,72,69,46,89,31,9]
selectionSort(a)
print(a)
if __name__ == '__main__':
main()
分治
a=[]
k=(int)(input("请输入k值"))
for i in range(k+1):
s=2**i
a.append(s)
print(a)
def Comparemax(x,y):
if x>y:
max=x
else:
max=y
return max
def Comparemin(x,y):
if x < y:
min = x
else:
min = y
return min
def findMax(a,left,right):
if left==right:
max=a[right]
return max
if right-left==1:
LM=a[left]
RM=a[right]
return (Comparemax(LM,RM))
if right - left > 1:
mid=(left+right)//2
LM=findMax(a,left,mid)
RM=findMax(a,mid+1,right)
return (Comparemax(LM,RM))
def findMin(a,left,right):
if left == right:
min = a[left]
return min
if right - left == 1:
LM = a[left]
RM = a[right]
return (Comparemin(LM, RM))
if right-left>1:
mid = (left + right) // 2
LM = findMin(a, left, mid)
RM = findMin(a, mid+1, right)
return (Comparemin(LM, RM))
def main():
print("最小值:")
print(findMin(a,0,len(a)-1))
print("最大值:")
print(findMax(a, 0, len(a)-1))
if __name__ == '__main__':
main()
顺序查找
def sequentialSearch(alist,item):#顺序查找
pos=0#初始查找位置
found=False#为找打数据对象
while pos<len(alist)and not found:
if alist[pos]==item:
found=True
else:
pos=pos+1
return found,pos
def main():
testlist=[1,3,33,8,37,29,32,15,5]
print(sequentialSearch(testlist,3))
print(sequentialSearch(testlist,15))
if __name__ == '__main__':
main()
二分查找递归
def _binarySearch(key,a,lo,hi):
if hi<=lo:return -1
mid=(lo+hi)//2
if a[mid]>key:
return _binarySearch(key,a,lo,mid)
elif a[mid]<key:
return _binarySearch(key,a,mid+1,hi)
else:return mid
def binarySearch(key,a):
return _binarySearch(key,a,0,len(a))
def main():
a=[1,13,26,33,45,55,68,72,83,99]
print("关键字列表索引位于",binarySearch(83,a))
print("关键字列表索引位于", binarySearch(10, a))
if __name__ == '__main__':
main()
二分查找非递归
def binarySearch(key,a):
low=0
high=len(a)-1
while low<=high:
mid=(low+high)//2
if a[mid]<key:low=mid+1
elif a[mid]>key:high=mid-1
else: return mid
return -1
def main():
a=[1,34,56,78,98,99.8]
print("关键字位于列表索引",binarySearch(99.8,a))
print("关键字位于列表索引", binarySearch(78, a))
print("关键字位于列表索引", binarySearch(23,a))
main()