第九节: 二分法搜索,冒泡排序与选择排序
选择排序: 每一趟从待排序的数据元素中选出最小(或最大)的一个元素,顺序放在已排好序的数列的最后,直到全部待排序的数据元素排完。
def SelSort(L):
for i in range(len(L)-1):
minIndex=i
minVal=L[i]
j=i+1
while j<len(L):
if minVal>L[j]:
minIndex=j
minVal=L[j]
print minVal
j+=1
temp=L[i]
L[i]=L[minIndex]
L[minIndex]=temp
return L
冒泡排序(大的数跑到最下面):
def bubbleSort(L):
for j in range(len(L)):
for i in range(len(L)-1):
if(L[i]>L[i+1]):
temp=L[i]
L[i]=L[i+1]
L[i+1]=temp
print L
第十节: 分治法,合并排序,异常
1)归并排序:
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+=1
else:
result.append(right[j])
j+=1
while (i<len(left)):
result.append(left[i])
i+=1
while (j<len(right)):
result.append(right[j])
j+=1
return result
def MergeSort(L):
print L
together=[]
if len(L)<2:
return L[:]
else:
middle=len(L)/2
left=MergeSort(L[:middle])
right=MergeSort(L[middle:])
together=Merge(left,right)
print 'Merge',together
return together
2)哈希函数:
def Test():
intSet=create(1,10)
insert(intSet,3)
print member(intSet,4)
def create(smallest,largest):
intSet=[]
for i in range(smallest,largest):intSet.append(None)
return intSet
def insert(inSet,e):
inSet[e]=1
def member(intSet,e):
return intSet[e]==1
def hashChar(c):
# c is a character
# function returns a different integer in the range 0 - 255 for each possible value of c
return ord(c)
def cSetCreate():
cSet = []
for i in range(256):
cSet.append(None)
return cSet
def cSetInsert(cSet, e):
cSet[hashChar(e)] = 1
def cSetSearch(cSet, e):
return cSet[hashChar(e)] == 1
第十二节: 调试的更多内容:背包问题,动态规划简介
重叠子问题:
def fib(n):
global numCalls
numCalls +=1
#print 'fib called with',n
if n<=1:
return 1 ##
else:
return fib(n-1)+fib(n-2)
def fastfib(n,memo):
global numCalls
numCalls+=1
#print 'fibl called with',n
if not n in memo:
memo[n]=fastfib(n-1,memo)+fastfib(n-2,memo)
return memo[n]
def fibl(n):
memo={0:1,1:1}
return fastfib(n,memo)
第十三节: 动态规划,重叠的子问题,最优子结构
def maxVal(w, v, i, aW):
print 'maxVal called with:',i,aW
global numcells
numcells+=1
if i == 0:
if w[i] <= aW: return v[i]
else:return 0
without_i = maxVal(w, v, i-1, aW)
print 'without_i',without_i
if w[i] > aW:
return without_i
else:
with_i = v[i] + maxVal(w, v, i-1, aW - w[i])
print max(with_i, without_i)
return max(with_i, without_i)
def fastMaxVal(w, v, i, aW, m):
try:
return m[(i, aW)] # to check whether the thing is in the memo or not
except KeyError:
if i == 0:
if w[i] <= aW:
m[(i, aW)] = v[i]
return v[i]
else:
m[(i, aW)] = 0
return 0
without_i = fastMaxVal(w, v, i-1, aW, m)
if w[i] > aW:
m[(i, aW)] = without_i
return without_i
else:
with_i = v[i] + fastMaxVal(w, v, i-1, aW - w[i], m)
res = max(with_i, without_i)
m[(i, aW)] = res
return res
def MaxVal0(w, v, i, aW):
m = {}
return fastMaxVal(w, v, i, aW, m)