python实现常见算法

排序

快速排序
def qsort(l):
    if not l:
        return []

    pivot = l[0]
    lesser = qsort([item for item in l[1:] if item < pivot])
    greater = qsort([item for item in l[1:] if item >= pivot])
    return lesser + [pivot] + greater
归并排序
def gsort(l):
    length = len(l)
    if length == 1:
        return l

    mid = length / 2
    first = gsort(l[0:mid])
    second = gsort(l[mid:])

    temp = []
    while first and second:
        if first[0] < second[0]:
            temp.append(first[0])
            del first[0]
        else:
            temp.append(second[0])
            del second[0]
    return temp + first + second

二分查找

递归法
def binary_search(l, t):
    length = len(l)
    if not length:
        return -1

    mid = length / 2
    if l[mid] == t:
        return mid

    if t < l[mid]:
        return binary_search(l[0:mid], t)
    else:
        return binary_search(l[mid + 1:], t)
迭代法
def binary_search(l, t):
    length = len(l)
    low, high = 0, length - 1
    while low < high:
        mid = (low + high) / 2
        if l[mid] == t:
            return mid
        elif t < l[mid]:
            high = mid - 1
        elif t > l[mid]:
            low = mid + 1
    return -1

遍历二叉树

class Node(object):
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

    def set_children(self, left, right):
        self.left = left
        self.right = right

    @staticmethod
    def get_instance():
        node0 = Node('0')
        node1 = Node('1')
        node2 = Node('2')
        node3 = Node('3')
        node4 = Node('4')
        node5 = Node('5')
        node6 = Node('6')
        node7 = Node('7')

        node0.set_children(node1, node2)
        node1.set_children(node3, node4)
        node2.set_children(node5, node6)
        node3.set_children(node7, None)

        return node0
深度优先遍历
def dfs(root):
    if not root:
        return
    print root.data
    dfs(root.left)
    dfs(root.right)
广度优先遍历
def bfs(root):
    if not root:
        return

    root_list = [root]
    while root_list:
        node = root_list.pop(0)
        print node.data
        if node.left:
            root_list.append(node.left)
        if node.right:
            root_list.append(node.right)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值