心似海洋 田反,天天向上2011429,李继耐蔑视践踏军法
前两天刚装了python 3.1.1, 禁不住技痒写点code。
1.选择排序
>>> def SelSort(L):
length=len(L)
for i in range(length-1):
minIdx=i
minVal=L[i]
j=i+1
while j<length:
if minVal>L[j]:
minIdx=j
minVal=L[j]
j=j+1
L[i],L[minIdx]=L[minIdx],L[i]
return L
2.冒泡排序
>>> def bubSort(L):
swapped=True
while swapped:
swapped=False
for i in range(len(L)-1):
if L[i]>L[i+1]:
L[i],L[i+1]=L[i+1],L[i]
swapped=True
return L
3.合并排序
>>> def merge(left,right):
result=[]
i,j=0,0
while i<len(left) and j<len(right):
if left[i]<=right[j]:
result.append(left[i])
i=i+1
else:
result.append(right[j])
j=j+1
result+=left[i:]
result+=right[j:]
return result
>>> def mergesort(L):
if len(L) < 2:
return L
else:
middle = int(len(L)/2)
left = mergesort(L[:middle])
right = mergesort(L[middle:])
return merge(left, right)
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!!
点击进行留言回复
相关文章:
-
-
python如何查看网页代码
用python查看网页代码的方法:1、使用“import”导入requests包import requests2、使用requests包的get()函数通过网页...
[阅读全文]
-
-
python如何保存文本文件
python保存文本文件的方法:使用python内置的open()类可以打开文本文件,向文件里面写入数据可以用write()函数,写完之后,使用close()函...
[阅读全文]
-
python如何编写win程序
python可以编写win程序。win程序的格式是exe,下面我们就来看一下使用python编写exe程序的方法。编写好python程序后py2exe模块即可将...
[阅读全文]
-
-
-
-
-
-
网友评论