博客
关于我
Python -- 算法实现
阅读量:804 次
发布时间:2023-03-05

本文共 1680 字,大约阅读时间需要 5 分钟。

二分搜索与二叉树排序实例解析

今天,我来分享两个有趣的数据结构与算法实例。第一个是二分搜索的实现,第二个是基于二叉树的排序算法。这些代码示例可以帮助我们更好地理解这两种数据结构的应用。

首先,让我们来看一下二分搜索的实现。下面是一个Python脚本,用于在数组中查找特定值:

def binSearch(arr, value):    low = 0    high = len(arr) - 1    while low <= high:        mid = int((low + high) / 2)        if value > arr[mid]:            low = mid + 1        elif value < arr[mid]:            high = mid - 1        else:            return mid    return -1a = [1, 22, 44, 55, 67]print(binSearch(a, 66))

这个函数通过不断缩小搜索范围来查找目标值。每次迭代都会将搜索区间减半,这使得时间复杂度为O(log n)。例如,当我们调用binSearch(a, 66)时,函数将返回-1,因为66不在数组中。

接下来,我们来看一下基于二叉树的排序算法。以下是一个Python脚本,用于对数组进行排序:

class BTree:    def __init__(self, value):        self.value = value        self.left = None        self.right = None    def insertLeft(self, value):        self.left = BTree(value)        return self.left    def insertRight(self, value):        self.right = BTree(value)        return self.rightdef inOrder(tree):    if tree.left:        inOrder(tree.left)    tree.show()    if tree.right:        inOrder(tree.right)def rInOrder(tree):    if tree.right:        rInOrder(tree.right)    tree.show()    if tree.left:        rInOrder(tree.left)def insert(tree, value):    if value < tree.value:        if tree.left:            insert(tree.left, value)        else:            tree.insertLeft(value)    else:        if tree.right:            insert(tree.right, value)        else:            tree.insertRight(value)arr = [5, 3, 4, 1, 2, 0, 9, 0, 9]Root = BTree(arr[0])for i in arr[1:]:    insert(Root, i)inOrder(Root)

这个代码实现了一个二叉搜索树,并通过递归的方式进行插入和遍历操作。inOrder函数从头到尾遍历树节点,按顺序输出元素值。rInOrder函数则从右向左遍历树节点,同样输出元素值。通过这个例子,我们可以直观地看到二叉树的应用场景。

以上代码实例展示了二分搜索和二叉树排序算法的基本原理和应用。希望这些代码能为您的学习提供帮助。

转载地址:http://vsafk.baihongyu.com/

你可能感兴趣的文章
Pytest中进行测试环境切换:pytest_addoption!
查看>>
pytest利用request fixture实现个性化测试需求详解
查看>>
pytest单元测试实战
查看>>
pytest单元测试框架
查看>>
Pytest参数详解 — 基于命令行模式
查看>>
pytorch cv2 plt transforms pause waitforbuttonpress一个完整的图片处理程序
查看>>
pytest学习和使用 - Pytest用例执行结果有哪几种状态?
查看>>
pytest实战技巧之参数化应用!
查看>>
Pytest实践:Python测试技术基础知识!
查看>>
Pytest接口自动化测试实战演练
查看>>
Pytest插件pytest-selenium-让自动化测试更简洁
查看>>
Pytest数据驱动怎么玩?实战教程来了!
查看>>
Pytest数据驱动怎么玩?实战教程来了!
查看>>
pytest文档25-conftest.py作用范围
查看>>
Pytest框架 之【用例执行顺序】
查看>>
Pytest框架中的测试用例执行方式!
查看>>
pytest框架快速入门-pytest运行时参数说明,pytest详解,pytest.ini详解
查看>>
Pytest框架环境切换实战教程!赶快收藏
查看>>
Pytest测试实战|Conftest.py详解
查看>>
Pytest测试框架快速搭建
查看>>