Python 官方文档:入门教程 => 点击学习
目录快速排序选择排序插入排序归并排序堆排序heapq模块栈队列二分查找快速排序 def quick_sort(_list): if len(_li
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)
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实现各种数据结构内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: 用python实现各种数据结构
本文链接: https://www.lsjlt.com/news/161333.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0