最近在上网课,复习了数据结构这一块内容,对快速排序又有了新的认识,代码的精简正是进步的表现。感谢internet
import randomdef quicksort(array): if len(array) < 2: return array else: pivot_index = 0 pivot = array[pivot_index] less_part = [ i for i in array[pivot_index + 1:] if i <= pivot ] great_part = [ i for i in array[pivot_index + 1:] if i > pivot ] return quicksort(less_part) + [pivot] + quicksort(great_part)if __name__ == '__main__': array = [random.randint(1, 20) for i in range(10)] s_a = quicksort(array) print(s_a)
输出结果:
>>> [1, 3, 3, 5, 5, 9, 9, 13, 13, 17]