排序算法
import random
import time
冒泡排序
arr = [5, 2, 1, 3, 8, 6]*1000
def bubble_sort():
for i in range(len(arr) - 1):
for j in range(1, len(arr) - i):
if arr[j - 1] > arr[j]:
arr[j - 1], arr[j] = arr[j], arr[j - 1]
bubble_sort()
print(arr)
选择排序
arr = list(range(1, 1000))
random.shuffle(arr)
def select_sort():
for i in range(len(arr) - 1):
min_index = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_index]:
min_index = j
if i != min_index:
arr[i], arr[min_index] = arr[min_index], arr[i]
插入排序
def insert_sort():
for i in range(1, len(arr)):
temp = arr[i]
insert_index = i
while insert_index > 0 and temp < arr[insert_index - 1]:
arr[insert_index] = arr[insert_index - 1]
insert_index -= 1
arr[insert_index] = temp
非原地快排
def quick_sort1(sort_arr: list):
"""
进行列表的划分 将列表划分为左 中 右
:param sort_arr:待划分的列表
:return: 最终的连接左中右的列表
"""
if len(sort_arr) <= 1:
return sort_arr
less, pivot, right = [], [sort_arr[0]], []
for i in range(1, len(sort_arr)):
if sort_arr[i] < pivot[0]:
less.append(sort_arr[i])
elif sort_arr[i] == pivot[0]:
pivot.append(sort_arr[i])
else:
right.append(sort_arr[i])
return quick_sort1(less) + pivot + quick_sort1(right)
原地排序
def quick_sort2(start: int, end: int):
"""
将序列的一部分划分为左小右大
:param start: 序列的起始位置
:param end: 序列的结束位置
:return: None
"""
if start < end:
s = start
e = end
flag = True
while s != e:
if arr[s] > arr[e]:
arr[s], arr[e] = arr[e], arr[s]
flag = not flag
if flag:
e -= 1
else:
s += 1
quick_sort2(start, e - 1)
quick_sort2(s + 1, end)
s = time.time()
quick_sort2(0, len(arr) - 1)
print(time.time() - s)
print(arr)
折半查找
import random
arr = [random.randint(1, 100) for i in range(50)]
def binary_search(s_list, key):
start = 0
end = len(s_list) - 1
while start <= end:
mid = (start + end) // 2
if s_list[mid] == key:
return mid
elif key > s_list[mid]:
start = mid + 1
else:
end = mid - 1
return -1
arr.sort()
print(arr)
print(binary_search(arr, 19))