mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4mobile wallpaper 5mobile wallpaper 6
283 字
1 分钟
查找算法笔记
2026-01-25

查找#

顺序查找#

无序表查找代码

def sequentialSearch(alist,item):
pos = 0
found = False
while pos < len(alist) and not found:
if alist[pos] == item:
found = True
else:
pos = pos + 1
return found

有序表查找代码

def orderedSequentialSearch(alist,item):
pos = 0
found = False
stop = False
while pos < len(alist) and not found and not stop:
if alist[pos] == item:
found = True
else:
if alist[pos] > item:
stop = True
else:
pos = pos + 1
return found

二分查找#

def binarySearch(alist,item):
first = 0
last = len(alist) - 1
found = False
while first <= last and not found:
midpoint = (first + last)//2
if alist[midpoint] == item:
found = True
else:
if item < alist[midpoint]:
last = midpoint - 1
else:
first = midpoint + 1
return found

递归实现

def binarySearch(alist,item):
if len(alist) == 0:
return False
else:
midpoint = len(alist)//2
if alist[midpoint] == item:
return True
else:
if item < alist[midpoint]:
return binarySearch(alist[:midpoint],item)
else:
return binarySearch(alist[midpoint+1:],item)

复杂度为O(log n)

排序#

冒泡排序#

def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp

插入排序#

nums = [5,3,6,4,1,2,8,7]
for i in range(1,len(nums)):
for j in range(i):
if nums[i] < nums[j]:
ins = nums[i]
nums.pop(i)
nums.insert(j,ins)
break
print(nums)

谢尔排序#

选择排序#

nums = [5,3,6,4,1,2,8,7]
res = []
while len(nums):
minInd = 0
for i in range(1,len(nums)):
if nums[i] < nums[minInd]:
minInd = i
temp = nums[minInd]
nums.pop(minInd)
res.append(temp)
print(res)

归并排序#

快速排序#

分享

如果这篇文章对你有帮助,欢迎分享给更多人!

查找算法笔记
https://chaojixin.ren/posts/查找算法及分析/
作者
超級の新人
发布于
2026-01-25
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

封面
Sample Song
Sample Artist
封面
Sample Song
Sample Artist
0:00 / 0:00