希尔排序
def shell_sort(list): """希尔排序,不稳定,最优时间复杂度根据步长决定,最坏时间复杂度O(n2)""" n = len(list) gap = n // 2 while gap >= 1: for i in range(gap, n): while i > 0: if list[i] < list[i - gap]: list[i], list[i - gap] = list[i - gap], list[i] i -= gap gap //= 2 return list
快速排序
def quick_sort(list, first, last): """快速排序,不稳定,最优时间复杂度O(logn),最坏时间复杂度O(n2)""" if first == last: return list mid_value = list[first] low = first high = last while low < high: while low < high and list[high] > mid_value: high -= 1 list[low] = list[high] while low < high and list[low] < mid_value: low += 1 list[high] = list[low] list[low] = mid_value quick_sort(list, first, low) quick_sort(list, low + 1, last) return list
归并排序
def merge_sort(list): """归并排序,稳定,最优最坏时间复杂度O(nlogn)""" n = len(list) if n == 1: return list mid = n // 2 left = merge_sort(list[:mid]) right = merge_sort(list[mid:]) left_pre = 0 right_next = 0 new_list = [] while left_pre < len(left) and right_next < len(right): if left[left_pre] < right[right_next]: new_list.append(left[left_pre]) left_pre += 1 else: new_list.append(right[right_next]) right_next += 1 new_list += left[left_pre:] new_list += right[right_next:] return new_list
快速查找
def double_search(list, item): """二分查找,最优时间复杂度O(1),最坏时间复杂度O(log2n)""" n = len(list) mid = n // 2 if mid >= 1: if list[mid] == item: return True else: if list[mid] > item: return double_search(list[:mid], item) else: return double_search(list[mid + 1:], item) else: return False l = [1, 2, 3, 4, 5, 6, 7] print(double_search(l, 100))