线性表基本操作
#定义线性表
class Lnode():
def __init__(self,last):
self.data=[None for i in range(100)] #数组长度
self.last=last #线性表的长度
#线性表的基本操作
def MakeEmpty(num):
PtrL=Lnode(num)
return PtrL
s=MakeEmpty(10)
#print(s.data[:s.last])#打印线性表
#print(s.last)#线性表的长度
#查找给定值的位置
def Find(x,L):
i=0
while i<L.last and x!=L.data[i]:
i+=1
if i==L.last:
return -1
else:
return i+1
#指定位置插入元素
def Insert(x,j,L):
i=L.last
if x<0 or x>L.last:
return -1
while i>=x:
L.data[i+1]=L.data[i]
i-=1
L.data[x]=j
return L.data[0:L.last+1]
#指定位置删除元素
def Del(x,L):
i=L.last
if x<0 or x>i:
return -1
while x<i:
L.data[x]=L.data[x+1]
x+=1
return L.data[:i-1]
L=Lnode(10)
for i in range(10):
L.data[i]=i
#print(Insert(3,6,L))
print(Del(0,L))
2 二分查找
def binary_search(x,M):
ma=len(M)-1
mb=0
while mb<=ma:
b=int((ma+mb)/2)
if M[b]>x:
ma=b-1
elif M[b]<x:
mb=b+1
else:
return b
return -1
M=[1,3,5,7,9]
print(binary_search(9,M))