常见排序算法

1.冒泡排序

def bubble_sort(alist):
        """冒泡排序"""
        n = len(alist)
        for j in range(0,n-1):
                # 走多少次
            count = 0 # 交换次数计数
            for i in range(0, n-1-j):
                # 从头走到尾,最后一个不用遍历到,到倒数第二个停止
                if alist[i]>alist[i+1]:
                    alist[i],alist[i+1]=alist[i+1],alist[i]
                    count += 1
            if count == 0:
                break
                # 没有交换说明已经排好顺序,直接退出循环
    
if __name__ == '__main__':
        li = [54,26,84,24,15]
        bubble_sort(li)
        print(li)

2.二叉树的前中后序遍历

class Node(object):
    """节点类"""
    def __init__(self, elem=-1, lchild=None, rchild=None):
        self.elem = elem
        self.lchild = lchild
        self.rchild = rchild

class Tree(object):
    """树类"""

    def __init__(self, root=None):
        self.root = root

    def add(self, elem):
        """为树添加节点"""
        node = Node(elem)
        # 如果树是空的,则对根节点赋值
        if self.root == None:
            self.root = node
        else:
            queue = []
            queue.append(self.root)
            # 对已有的节点进行层次遍历
            while queue:
                # 弹出队列的第一个元素
                cur = queue.pop(0)
                if cur.lchild == None:
                    cur.lchild = node
                    return
                elif cur.rchild == None:
                    cur.rchild = node
                    return
                else:
                    # 如果左右子树都不为空,加入队列继续判断
                    queue.append(cur.lchild)
                    queue.append(cur.rchild)

    def breadth_travel(self):
        """广度遍历利用队列实现树的层次遍历"""
        if self.root == None:
            return
        queue = []
        queue.append(self.root)
        while queue:
            node = queue.pop(0)
            print(node.elem,end='')
            if node.lchild != None:
                queue.append(node.lchild)
            if node.rchild != None:
                queue.append(node.rchild)

    # 深度遍历:前序 中序 后序
    def preorder(self,node):
        # 前序 根node 左 右
        if node is None:
            return
        print(node.elem,end='')
        self.preorder(node.lchild)
        self.preorder(node.rchild)

    def inorder(self,node):
        if node is None:
            return
        self.inorder(node.lchild)
        print(node.elem,end='')
        self.inorder(node.rchild)

    def postorder(self,node):
        if node is None:
            return
        self.postorder(node.lchild)
        self.postorder(node.rchild)
        print(node.elem,end='')



if __name__ == '__main__':
    tree = Tree()
    tree.add(0)
    tree.add(1)
    tree.add(2)
    tree.add(3)
    tree.add(4)
    tree.add(5)
    tree.add(6)
    tree.add(7)
    tree.add(8)
    tree.add(9)
    # tree.breadth_travel()
    # print(' ')
    tree.preorder(tree.root)
    print(' ')
    # tree.inorder(tree.root)
    # print(' ')
    # tree.postorder(tree.root)

3.二分查找

def binary_search(alist,item):
    '''二分查找:递归,每次传入新列表'''
    n = len(alist)
    if n > 0:# 递归终止条件
        mid = n//2
        if alist[mid] == item:
            return True
        elif item

4.快速排序

def quick_sort(alist,first,last):
    """快排1"""
    if first >= last:
        return
    mid_value = alist[first] # 第一个值设为第一个值
    low = first
    high = last
    while low=mid_value:
            high -= 1
        alist[low]=alist[high]
        # low+=1
        # low右移
        while low

5.插入排序

def insert_sort(alist):
    n=len(alist)
    # 从右边无序序列中取多少个执行,除过第一个不执行
    for j in range(1,n): #n
        # i代表内层循环起始值
        # 假设第一个元素有序,从第二个元素开始
        i = j # 从右边无序序列中取第一个元素 i位置的元素插入到前面正确位置。
        while i>0 : # n
            if alist[i]

6.选择排序

def select_sort(alist):
    n = len(alist)
    for j in range(n-1):
        # j:0~n-2
        min_list=j  #索引
        for i in range(j+1,n): # n 是长度
            if alist[min_list] > alist[i]:
                min_list=i
        alist[j],alist[min_list] = alist[min_list],alist[j]

if __name__ == '__main__':
    li = [54,26,84,24,15]
    select_sort(li)
    print(li)

7.时间装饰器

import time
def time_deco(func):
    def wrapper(*args,**kwargs):
        start_time = time.time()
        func(*args,**kwargs)
        time_end=time.time()
        print('运行时间为:',time_end-start_time)
    return wrapper

8.希尔排序

def shell_sort(alist):
    """希尔排序"""
    n = len(alist)
    gap = n//2 # 步长

    while gap>0:
        # Gap变化到0时退出
        for j in range(gap,n):
            i=j
            while i>0:
                # 与插入算法的区别是gap步长不是1
                if alist[i]

你可能感兴趣的:(python)