冒泡,选择,快速-排序
冒泡
l = [5, 9, 1, 3, 8, 2, 7, 4] for i in range(len(l)): for j in range(len(l) - i - 1): if l[j] > l[j + 1]: l[j], l[j + 1] = l[j + 1], l[j] print(l)
选择
l = [5, 9, 1, 3, 8, 2, 7, 4] for i in range(len(l)): min_index = l.index(min(l[i:]), i) l[i], l[min_index] = l[min_index], l[i] print(l)
快排
def quick_sort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [] right = [] for i in range(len(arr)): if i != len(arr) // 2: if arr[i] < pivot: left.append(arr[i]) else: right.append(arr[i]) print(left, pivot, right) return quick_sort(left) + [pivot] + quick_sort(right) l = [5, 9, 1, 3, 8, 2, 7, 4] print(quick_sort(l))