def bubble_sort(L): '''Sort the items in L in non-descending order.''' for i in range(0, len(L)): for j in range(0, len(L) - i - 1): if L[j] > L[j + 1]: L[j], L[j + 1] = L[j + 1], L[j] return L def find_min(L, i): '''Return the index of the smallest item in L[i:]''' smallest = i # The index of the smallest so far for j in range(i + 1, len(L)): if L[j] < L[smallest]: smallest = j return smallest def selection_sort(L): '''Sort the items in L in non-descending order.''' i = 0 # L[:i] is sorted. while i < len(L): smallest = find_min(L, i) #swap temp = L[smallest] L[smallest] = L[i] L[i] = temp i += 1 return L def selection_sort2(L): '''Sort the items in L in non-descending order.''' for i in range(len(L)): smallest = find_min(L, i) L[smallest], L[i] = L[i], L[smallest] return L def insert(L, i): '''Move L[i] to where it belongs in L[:i].''' v = L[i] while i > 0 and L[i - 1] > v: L[i] = L[i - 1] i -= 1 L[i] = v def insertion_sort(L): '''Sort the items in L in non-descending order.''' i = 0 # L[:i] is sorted. while i != len(L): insert(L, i) i += 1 return L def insertion_sort2(L): '''Sort the items in L in non-descending order.''' for i in range(len(L)): insert(L, i) return L def merge(left, right): '''Return the list made by merging sorted lists left and right.''' result = [] i ,j = 0, 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i = i + 1 else: result.append(right[j]) j = j + 1 # One of the sublists has elements left over; the other is empty. Copying # both makes sure we get it. result += left[i:] result += right[j:] return result def merge_sort(L): '''Sort the items in L in non-descending order.''' if len(L) < 2: return L else: middle = len(L) / 2 left = merge_sort(L[:middle]) right = merge_sort(L[middle:]) return merge(left, right) selection_sort([1,3,56,54,3,8,2,33])