用python实现各种数据结构
程序员文章站
2022-03-25 08:43:33
目录快速排序选择排序插入排序归并排序堆排序heapq模块栈队列二分查找快速排序 def quick_sort(_list): if len(_list) < 2:...
快速排序
def quick_sort(_list): if len(_list) < 2: return _list pivot_index = 0 pivot = _list(pivot_index) left_list = [i for i in _list[:pivot_index] if i < pivot] right_list = [i for i in _list[pivot_index:] if i > pivot] return quick_sort(left) + [pivot] + quick_sort(right)
选择排序
def select_sort(seq): n = len(seq) for i in range(n-1) min_idx = i for j in range(i+1,n): if seq[j] < seq[min_inx]: min_idx = j if min_idx != i: seq[i], seq[min_idx] = seq[min_idx],seq[i]
插入排序
def insertion_sort(_list): n = len(_list) for i in range(1,n): value = _list[i] pos = i while pos > 0 and value < _list[pos - 1] _list[pos] = _list[pos - 1] pos -= 1 _list[pos] = value print(sql)
归并排序
def merge_sorted_list(_list1,_list2): #合并有序列表 len_a, len_b = len(_list1),len(_list2) a = b = 0 sort = [] while len_a > a and len_b > b: if _list1[a] > _list2[b]: sort.append(_list2[b]) b += 1 else: sort.append(_list1[a]) a += 1 if len_a > a: sort.append(_list1[a:]) if len_b > b: sort.append(_list2[b:]) return sort def merge_sort(_list): if len(list1)<2: return list1 else: mid = int(len(list1)/2) left = mergesort(list1[:mid]) right = mergesort(list1[mid:]) return merge_sorted_list(left,right)
堆排序heapq模块
from heapq import nsmallest def heap_sort(_list): return nsmallest(len(_list),_list)
栈
from collections import deque class stack: def __init__(self): self.s = deque() def peek(self): p = self.pop() self.push(p) return p def push(self, el): self.s.append(el) def pop(self): return self.pop()
队列
from collections import deque class queue: def __init__(self): self.s = deque() def push(self, el): self.s.append(el) def pop(self): return self.popleft()
二分查找
def binary_search(_list,num): mid = len(_list)//2 if len(_list) < 1: return flase if num > _list[mid]: binarysearch(_list[mid:],num) elif num < _list[mid]: binarysearch(_list[:mid],num) else: return _list.index(num)
到此这篇关于用python实现各种数据结构的文章就介绍到这了,更多相关python实现各种数据结构内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
下一篇: C++函数模板介绍