冒泡排序
#coding:utf-8
def duble_sort(alist):
“冒泡排序”
n=len(alist)
for j in range(0,n-1):
count = 0
for i in range(0,n-1-j):
if alist[i]>alist[i+1]:
alist[i],alist[i+1] =alist[i+1], alist[i]
count+=1
if count0:
return
if name"main":
li=[1,2,3,4,5]
print(li)
duble_sort(li)
print(li)
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
选择排序
#coding:utf-8
def select_sort(alist):
“选择排序”
n=len(alist)
for j in range(0,n-1):
min_index=j
for i in range(j+1,n):
if alist[min_index]>alist[i]:
min_index=i
alist[min_index],alist[j] =alist[j], alist[min_index]
if name==“main”:
li=[2,9,1,6,91]
print(li)
select_sort(li)
print(li)
[2, 9, 1, 6, 91]
[1, 2, 9, 6, 91]
插入序列
#coding:utf-8
def insert_sort(alist):
“”“插入序列”""
n=len(alist)
for j in range(1,n):
i=j
while i >0:
if alist[i]<alist[i-1]:
alist[i],alist[i-1]=alist[i-1],alist[i]
i-=1
else:
break
if name"main":
li=[11,2,3,34,5]
print(li)
insert_sort(li)
print(li)
希尔序列:
#coding:utf-8
def shell_sort(alist):
“”“插入序列”""
n=len(alist)
gap=n//2
while gap>=1:
for i in range(gap,n):
while i>0:
if alist[i]<alist[i-gap]:
alist[i],alist[i-gap]=alist[i-gap],alist[i]
i-=gap
else:
break
gap//=2
if name"main":
li=[11,2,3,34,5]
print(li)
shell_sort(li)
print(li)
快速排序
#coding:utf-8
def quick_sort(alist,first,last):
if first>=last:
return
n=len(alist)
mid_value=alist[first]
low=first
high=last
while low<high:
if low<high and alist[high]>mid_value:
high-=1
alist[low]=alist[high]
if low<high and alist[low]<mid_value:
low+=1
alist[high]=alist[low]
alist[low]=mid_value
quick_sort(alist,first,low-1)
quick_sort(alist,low+1,last)
if name==“main”:
li=[11,2,3,34,5]
print(li)
quick_sort(li,0,len(li)-1)
print(li)
[11, 2, 3, 34, 5]
[2, 3, 5, 11, 34]
#coding:utf-8
def merge_sort(alist):
n=len(alist)
if n<=1:
return alist
mid=n//2
left_li=merge_sort(alist[:mid])
right_li=merge_sort(alist[mid:])
left_point,right_point=0,0
result=[]
while left_point<len(left_li)and right_point<len(right_li):
if left_li[left_point]<right_li[right_point]:
result.append(left_li[left_point])
left_point+=1
else:
result.append(right_li[right_point])
right_point+=1
result+=left_li[left_point:]
result+=right_li[right_point:]
return result
归并排序
if name==“main”:
li=[11,2,3,34,5]
print(li)
sort_li=merge_sort(li)
print(sort_li)
二分法搜索
#coding:utf-8
def binary_sort(alist,item):
n=len(alist)
mid=n//2
if n>0:
if alist[mid]==item:
return True
elif item<alist[mid]:
return binary_sort(alist[:mid],item)
else:
return binary_sort(alist[mid+1:],item)
return False
if name==“main”:
li=[11,2,3,34,5]
print(binary_sort(li,5))
print(binary_sort(li,15))