用python实现各种数据结构
目录
- 快速排序
- 选择排序
- 插入排序
- 归并排序
- 堆排序heapq模块
- 栈
- 队列
- 二分查找
快速排序
def quick_sort(_list): if len(_list) < 2: zdPQUqb 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 += http://www.cppcns.com1 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 nsmallesthttp://www.cppcns.com(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.app编程客栈end(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实现各种数据结构内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
精彩评论