线性表

线性表基本操作

#定义线性表
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))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值