常见算法
一.冒泡排序
# 冒泡排序O(n^2) def bubble_sort(li): for i in range(len(li)-1): for j in range(len(li)-1-i): if li[j] >li[j+1]: li[j],li[j+1] = li[j+1],li[j]
二.选择排序
# 选择排序 def select_sort(li): for i in range(len(li)): minloc = i for j in range(i+1,len(li)): if li[minloc]>li[j]: li[minloc],li[j] = li[j],li[minloc]
三.插入排序
def insert_sort(li): for i in range(1,len(li)): temp = li[i] j = i - 1 while j>=0 and li[j]>temp: li[j+1] = li[j] j = j - 1 li[j+1] = temp
四.快速排序
#快速排序 def partition(data,left,right): tmp =data[left] while left < right: while left < right and data[right]>= tmp: right = right -1 data[left] = data[right] while left <right and data[left]<= tmp: left = left +1 data[right] = data[left] data[left] = tmp return left def quick_sort(data,left,right): if left < right: mid = partition(data,left,right) quick_sort(data,left,mid) quick_sort(data,mid+1,right)
五.计数排序
def count_sort(li): count = [0 for i in range(1000)] for i in li : count[i]+=1 li.clear() for i,x in enumerate(count): for j in range(x): li.append(i) li = [22, 32, 32, 64, 3, 342, 65, 22] count_sort(li) print(li)
六.单链表
class Hero(): def __init__(self, no=None, name=None, nickname=None, pNext=None): self.no = no self.name = name self.nickname = nickname self.pNext = pNext def addHero(head, hero): cur = head while cur.pNext != None: cur = cur.pNext ### 已经找到位置 cur.pNext = hero def getAll(head): cur = head while cur.pNext != None: cur = cur.pNext print("编号是:%s, 名字是:%s, 昵称是:%s" % (cur.no, cur.name, cur.nickname)) head = Hero() h1 = Hero(1, '宋江', '及时雨') addHero(head, h1) h2 = Hero(2, '卢俊义', '玉麒麟') addHero(head, h2) h3 = Hero(3, '误用', '智多星') addHero(head, h3) h4 = Hero(4, '公孙胜', '入云龙') addHero(head, h4) getAll(head)