经典算法 之 顺序查找 Python实现

活动地址:CSDN21天学习挑战赛


1. 算法

定义:任何被明确定义的计算过程都可以称作算法,它将某个值或一组值作为输入,并产生某个值或一组值作为输出。所以算法可以被称作将输入转为输出的一系列的计算步骤。

Informally, an algorithm is any well-defined computational procedure that takes some value, or set of values, as input and produces some value, or set of values, as output. An algorithm is thus a sequence of computational steps that transform the input into the output.


1.1 数据结构

程序 = 数据结构 + 算法

数据结构:相互之间存在的一种或多种特定关系的数据元素的集合

数据元素:是组成数据的、有一定意义的基本单元,在计算机中通常作为整体处理,也称record。由数据项(最小单元)组成。

数据对象:性质相同的数据元素的集合,数据的子集。

数据:符号集合。
在这里插入图片描述


1.2 算法效率

算法效率:包括时间复杂度空间复杂度

  • 时间复杂度:语句总的执行次数T(n)是关于问题规模n的函数,分析T(n)关于n的变化情况并确定T(n)的数量集。

T ( n ) = O ( f ( n ) ) T(n)=O(f(n)) T(n)=O(f(n))

用大写O()来体现算法时间复杂度的记法,称之为O记法

常见的时间复杂度有(由低到高):
O ( 1 ) < O ( log ⁡ 2 n ) < O ( n ) < O ( n log ⁡ 2 n ) < O ( n 2 ) < O ( n 3 ) < O ( 2 n ) < O ( n ! ) O(1)<O(\log _{2} n)<O(n)<O( n\log _{2} n)<O( n^{2})<O(n^{3})<O( 2^{n} )<O(n!) O(1)<O(log2n)<O(n)<O(nlog2n)<O(n2)<O(n3)<O(2n)<O(n!)

  • 空间复杂度:计算算法需要的存储空间实现

S ( n ) = O ( f ( n ) ) S(n)=O(f(n)) S(n)=O(f(n))

其中,n为问题规模,f(n)为语句关于n所占存储空间的函数。


2. 顺序查找

从线性表一端开始,逐个检查关键字是否满足给定的条件。
若查找成功,返回元素在线性表的位置,否则返回查找失败信息。


2.1 原理

  • 输入
    1. n个数的序列,通常直接存放在数组中,可以是任何顺序。
    2. 待查找元素key
  • 输出
    查找成功:返回元素所在位置的编号。
    查找失败:返回-1或自定义失败标识。

伪代码示例:

i = 1
while i <= A.length
    if A[i] == key
        return i
    i++
return -1

2.2 优缺点

优点:对数据元素的存储没有需求,顺序存储或链式存储皆可;对表中记录的有序性也没有要求,无论记录是否按关键码有序,均可应用;

缺点:是当n较大时,平均查找长度较大,效率低,时间复杂度O(n)


3. python实践

python内置函数顺序查找:

mylist = [1,2,3,4,5,6]
print(5 in mylist)		# 查找5是否在列表中
print(mylist.index(5))	# 返回第一个数据5的下标
print(mylist.index(5,2,5))  # 返回从下标2到5(不含)查找数据5
print(mylist.count(5))	# 返回数据5的个数

3.1 遍历有序列表

# 遍历有序列表
def sequential_search(list, key):
    for i in range(len(list)):
        if list[i] == key:
            return i
    else:
        return False


if __name__ == '__main__':
    list_0 = [1,2,3,4,5,6,7,8,9,10]
    result0 = sequential_search(list_0, 10)
    result1 = sequential_search(list_0, 11)
    print(result0, result1)
9 False

3.2 遍历无序列表

  1. 创建节点类Node,节点(Node)是实现链表的基本模块,包含节点自身的数据,称为“数据域”, 和对下一个节点的“引用”。
# 创建节点类Node,节点(Node)是实现链表的基本模块
class Node:
	def __init__(self, initdata):
		self.data = initdata
		self.next = None

	def getData(self):
		return self.data

	def getNext(self):
		return self.next

	def setData(self, newdata):
		self.data - newdata

	def setNext(self, newnext):
		self.next = newnext
  1. 创建无序列表类UnorderedList,无序列表通过一个节点的集合来实现,每个节点包括对下一个节点的引用。
# 创建无序列表类UnorderedList
class UnorderdList:
	def __init__(self):
		self.head = None

	def isEmpty(self):
		return self.head == None

	def add(self, item):
		temp = Node(item)
		temp.setNext(self.head)
		self.head = temp

	def size(self):
		current = self.head
		count = 0
		while current != None:
			count = count + 1
			current = current.getNext()

		return count
			
	def search(self, item):
		current = self.head
		found = False
		while current != None and not found:
			if current.getData() == item:
				found = True
			else:
				current = current.getNext()

		return found

	def remove(self, item):
		current = self.head
		previous = None
		found = False
		while not found:
			if current.getData() == item:
				found = True
			else:
				previous = current
				current = current.getNext()

		if previous == None:
			self.head = current.getNext()
		else:
			previous.seteNext(current.getNext())
mylist = UnorderdList()
mylist.add(1)
mylist.add(2)
mylist.add(3)
mylist.add(4)
mylist.add(5)
mylist.add(6)

print(mylist.size())
print('查找key=6的索引:', mylist.search(6))

print('--------------')
mylist.remove(6)
print(mylist.size())
print('移除6,查找key=6的索引:', mylist.search(6))

6
查找key=6的索引: True
--------------
5
移除6,查找key=6的索引: False

3.3 应用:求最大、最小值

def Max(alist):
	pos = 0	   # 初始位置
	imax = alist[0]
	while pos < len(alist):
		if alist[pos] > imax:
			imax = alist[pos]
		pos = pos + 1
	return imax

def Min(alist):
	pos = 0
	imin = alist[0]
	for item in alist:
		if item < imin:
			imin = item
	return imin

另外,还可以尝试寻找有序列表的中位数等。


参考

1.一文学懂经典算法系列之:顺序查找
2.张清云.《Python数据结构学习笔记》(ISBN:9787113269999)


@夏日回

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值