def selection_sort(data): for j in range(0, len(data) - 1): lowest = j for i in range(j + 1, len(data)): if data[i] < data[lowest]: lowest = i if j != lowest: data[j], data[lowest] = data[lowest], data[j] if __name__ == '__main__': import animation animation.play_sorting_movie(selection_sort)
def bubble_sort(data): for curstep in range(len(data) - 1, 0, -1): for i in range(curstep): if data[i] > data[i + 1]: data[i], data[i + 1] = data[i + 1], data[i] if __name__ == '__main__': import animation animation.play_sorting_movie(bubble_sort)
# see <https://en.wikipedia.org/wiki/Quicksort#Choice_of_pivot>. pivot = data[stop - 1] # Split data[start:stop] into two piles, # those above the pivot and those below. i = start j = stop - 1 while i < j: item = data[i] if item >= pivot: j -= 1 data[i] = data[j] data[j] = item else: i += 1 # Swap the pivot to the middle, between the two piles. data[stop - 1] = data[i] data[i] = pivot # Sort both piles and we're done. sort_slice(start, i) sort_slice(i + 1, stop) sort_slice(0, len(data)) if __name__ == '__main__': import animation animation.play_sorting_movie(quicksort)
# Choose a pivot. We do the simplest possible thing here, but # see <https://en.wikipedia.org/wiki/Quicksort#Choice_of_pivot>. pivot = data[stop - 1] # Split data[start:stop] into two piles, # those above the pivot and those below. i = start j = stop - 1 while i < j: item = data[i] if item >= pivot: j -= 1 data[i] = data[j] data[j] = item else: i += 1 # Swap the pivot to the middle, between the two piles. data[stop - 1] = data[i] data[i] = pivot # Sort both piles and we're done. sort_slice(start, i) sort_slice(i + 1, stop) sort_slice(0, len(data)) if __name__ == '__main__': import animation animation.play_sorting_movie(quicksort)
def insertion_sort(data): for j in range(1, len(data)): i = j - 1 value = data[j] while i >= 0 and data[i] > value: data[i + 1] = data[i] i -= 1 data[i + 1] = value if __name__ == '__main__': import animation animation.play_sorting_movie(insertion_sort)