四种经典查找算法(python实现)

四种经典排序算法(python实现)

  • 顺序查找
  • 二分查找
  • 差值查找
  • 二叉树查找

 

一、顺序查找

'''
顺序查找:
1.算法思想:顺序查找,对于一个无序序列,遍历数组中的所有元素,对比每一个元素是否和要查询
          元素相等
2.时间复杂度:o(n)
3.空间复杂度:o(1)
'''

代码实现:

def sequential_search(li, key):
    for i in range(len(li)):
        if li[i] == key:
            return i
    else:
        return False

if __name__ == "__main__":
    li = [1, 5, 8, 123, 22, 54, 7, 99, 300, 222]
    print(sequential_search(li, 54))
    print(sequential_search(li, 87))

 

二、二分查找

'''
二分查找:
1.算法思想:折半查找,对于一个有序序列
2.时间复杂度:o(logn),最优时间复杂度o(1)
3.空间复杂度:o(1)
'''

 

代码实现:

def binary_search(li, item):
    first = 0
    last = len(li) - 1

    while first <= last:
        midpoint = int((first + last) / 2)
        if li[midpoint] == item:
            return True
        elif item < li[midpoint]:
            last = midpoint - 1
        else:
            first = midpoint + 1
    return False

li = [0, 2, 3, 4, 5, 6]
print(binary_search(li, 5))
print(binary_search(li, 7))

 

 

三、差值查找

'''
差值查找:
1.算法思想:类似于二分查找,只是中间数的求法不一样
mid = low + int((high - low) * (key - lis[low])/(lis[high] - lis[low]))
2.时间复杂度:o(logn)
3.空间复杂度:o(1)
'''

代码实现:

def binary_search(li, key):
    low = 0
    high = len(li) - 1
    time = 0
    while low  <= high:
        time += 1
        mid = low + int((high - low) * (key - li[low])/(li[high] - li[low]))
        if li[mid] == key:
            return True
        elif li[mid] < key:
            low = mid +1
        elif li[mid] > key:
            high = mid - 1
    if low >= high:
        return False



li = [0, 2, 3, 4, 5, 6]
print(binary_search(li, 5))
print(binary_search(li, 7))

 

四、二叉树查找

'''
二叉树查找:
1.算法思想:二插查找树,如任意节点的左子树不空,则左子树上所有及节点的值均小于
         它的根节点的值;若任意节点的右子树不空,则右子树上所有节点的值均大于
         它的节点的值;任意节点的左子树、右子树也分别为二叉树。
2.时间复杂度:o(logn),在插入或者删除元素的时候,如果树没有保持平衡,则时间复杂度为o(n)
3.空间复杂度:
'''


代码实现:

class TreeNode(object):
    '''定义树节点'''
    def __init__(self, item, ltree=None, rtree=None):
        self.item = item
        self.ltree = ltree
        self.rtree = rtree

class BinarySortTree(object):
    '''基于BSTree类的二叉查找树,维护一个根节点的指针。'''
    def __init__(self, root=None):
        self.root = root

    def search(self, key):
        '''关键字搜索,返回节点或者None'''
        bt = self.root
        while bt:
            if key < bt.item:
                bt = bt.ltree
            elif key > bt.item:
                bt = bt.rtree
            else:
                return bt.item
        return False

    def insert(self, key):
        '''插入'''
        bt = self.root
        if not bt:
            self.root = TreeNode(key)
            return
        while True:
            if key < bt.item:
                if bt.ltree is None:
                    bt.ltree = TreeNode(key)
                    return
                bt = bt.ltree
            elif key > bt.item:
                if bt.rtree is None:
                    bt.rtree = TreeNode(key)
                    return
                bt = bt.rtree
            else:
                bt.item = key
                return



    def delete(self, key):
        '''删除'''
        p = None
        q = self.root
        if not q:
            print("空树!!")
            return
        while q and q.item != key:
            p = q
            if key < q.item:
                q = q.ltree
            else:
                q = q.rtree
            if not q:
                return
        '''while循环找到了要删除的节点,用q引用。而p是q的父节点或者None'''

        '''下面考虑q节点的左子树为空的情况'''
        if not q.ltree:
            #1.如果q节点是根节点
            if p is None:
                self.root = q.rtree
            #2.如果q节点是p的左子树节点
            elif q is p.ltree:
                p.ltree = q.rtree
            #3.如果q节点是p节点的右子树节点
            else:
                p.rtree = q.rtree
            return
        '''下面考虑节点q的左子树不为空的情况'''
        #1.把q节点的右子树放到它的左子树
        r = q.ltree
        while r.rtree:
            r = r.rtree

        r.rtree = q.rtree

        #2.删除节点
        if p is None:
            self.root = q.ltree
        elif p.ltree is q:
            p.ltree = q.ltree
        else:
            p.rtree = q.ltree


    def iter(self):
        '''遍历二叉树,展示我们创建的二叉查找树'''
        if self.root == None:
            return
        queue = []
        queue.append(self.root)
        while queue:
            node = queue.pop(0)
            print(node.item)
            if node.ltree != None:
                queue.append(node.ltree)
            if node.rtree != None:
                queue.append(node.rtree)

if __name__ == "__main__":
    li = [1, 2, 3, 4, 5, 6, 7, 8]
    bs_tree = BinarySortTree()
    for i in range(len(li)):
        bs_tree.insert(li[i])
    print(bs_tree)
    bs_tree.iter()
    print(bs_tree.search(6))
    print(bs_tree.delete(5))
    bs_tree.insert(20)
    bs_tree.iter()

 

你可能感兴趣的:(数据结构与算法,小菜鸟的python进阶之路)