算法——二分查找、选择排序、快速排序

二分查找

二分查找的复杂度为O(nlogn),使用二分查找的前提是该序列为一个有序数列。

def binary_search(arr, item):
	low = 0
	high = len(arr) - 1
	while low <= high:
		mid = (low + high) // 2
		guess = list[mid]
		if guess == item:
			return guess
		elif guess > item:
			high = mid - 1
		else:
			low = low + 1
	return None

选择排序

选择排序的复杂度为O( n 2 n^2 )。

# method 1
def findSmallest(arr):
	smallest = arr[0]
	smallest_index = 0
	for i in range(1, len(arr)):
		if arr[i] < smallest:
			smallest = arr[i]
			smallest_index = i
	return smallest_index
def SelectionSort(arr):
	new_arr = []
	for i in range(len(arr)):
		smallest = findSmallest(arr)
		new_arr.append(arr.pop(smallest))
	return new_arr
# method 2
new_arr = sorted(arr)

快速排序

快速排序的复杂度为O(nlogn)

def quickSort(arr):
	if len(arr) < 2:
		return arr
	else:
		pivot = arr[0]
		less = [i for i in arr[1:] if i <= pivot]
		greater = [i for i in arr[1:] if i > pivot]
		return quickSort(less) + [pivot] + quickSort(greater)

递归求和

def sum(list):
	if list == []:
		return 0
	else:
		return list[0] + sum(list[1:])
发布了19 篇原创文章 · 获赞 17 · 访问量 1454

猜你喜欢

转载自blog.csdn.net/weixin_43839651/article/details/105647371