冒泡排序
def sort(alist):
lenth = len(alist)
for j in range(lenth - 1):
for i in range(lenth - 1):
if alist[i]> alist[i + 1]: # 两两比较大小,谁大往后走
alist[i], alist[i + 1] = alist[i + 1], alist[i]
return alist
二分查找
def findValue(alist, item):
left = 0 # 序列中第一个元素下标
right = len(alist) - 1 # 最后一个元素下标
find = False
while left <= right:
mid = (left + right) // 2 # 中间元素下标
if item < alist[mid]: # 查找的值小于中间元素,查找的值存在于中间元素左侧
right = mid - 1
elif item > alist[mid]: # 大于中间元素 在中间元素右侧
left = mid + 1
else:
find = True
break
return find
选择排序
def sort1(alist):
for j in range(len(alist)):
max_indedx = 0
for i in range(1, len(alist) - j):
if alist[max_indedx] < alist[i]:
max_indedx = i
alist[max_indedx], alist[len(alist) - j - 1] = alist[len(alist) - j - 1], alist[max_indedx]
return alist
插入排序
def sort_hash(alist:list):
gap = len(alist) // 2
while gap >= 1:
for i in range(gap,len(alist)):
while i > 0:
if alist[i] < alist[i-gap]:
alist[i],alist[i-gap] = alist[i-gap],alist[i]
i -= gap
else:
break
gap //= 2
return alist
希尔排序
def sort(alist):
gap = len(alist) // 2
while gap >= 1:
for i in range(gap, len(alist)):
while i > 0:
if alist[i] < alist[i - gap]:
alist[i], alist[i - gap] = alist[i - gap], alist[i]
i = i - gap
else:
break
gap = gap // 2
return alist
快速排序
# 完整code
def sort(alist,start,end):
low = start
high = end
# 结束递归的条件
if low > high:
return
mid = alist[low] # 基数
while low < high:
while low < high:
# 向左偏移high
if alist[high] > mid:
high -= 1
else:
alist[low] = alist[high]
break
while low < high:
if alist[low] < mid:
low += 1
else:
alist[high] = alist[low]
break
if low == high:
alist[low] = mid
# 将sort递归作用在基数左侧子序列
sort(alist,start,high-1)
# 将sort递归作用在基数右侧子序列
sort(alist,high + 1,end)
return alist
def sort(alist):
if len(alist) < 2:
return alist
pivot = alist[0]
less = [i for i in alist[1:] if i <= pivot]
greater = [i for i in alist[1:] if i > pivot]
return sort(less) + [pivot] + sort(greater)
if __name__ == '__main__':
print(sort([5,1,2,4,7,9,3]))