120 likes | 142 Views
Sorting Algorithms. Chris Graves February 20, 2013 18.304. Bogosort. def bogosort (items): while not isSorted (items): items = shuffle(items) return items. Bubble Sort. def bubbleSort (items): n = len (items) while not n == 0: newn = 0 for i in range(1, n):
E N D
Sorting Algorithms Chris Graves February 20, 2013 18.304
Bogosort defbogosort(items): while not isSorted(items): items = shuffle(items) return items
Bubble Sort defbubbleSort(items): n = len(items) while not n == 0: newn = 0 for i in range(1, n): if items[i-1] > items[i] (items[i-1], items[i]) = (items[i], items[i-1]) newn = i n = newn return items
Heapsort defheapsort(items): build_max_heap(items) for i in reversed(range(1, len(items))): items[0], items[i] = items[i], items[0] items.heap_size -= 1 max_heapify(items, 0)
Merge Sort defmerge_sort(items): if len(items) <= 1: return items middle = len(items) // 2 left = items[:middle] right = items[middle:] left = merge_sort(left) right = merge_sort(right) return merge(left, right)
Merge Sort def merge(left, right): result = [] while len(left) > 0 or len(right) > 0: if len(left) > 0 and len(right) > 0: if left[0] <= right[0]: result.append(left[0]) left = left[1:] else: result.append(right[0]) right = right[1:] else if len(left) > 0: result.extend(left) return result else if len(right) > 0: result.extend(right) return result return result
Quicksort def quicksort(items): if len(items) ≤ 1: return items pivot = rand_pop(items) less = [] greater = [] for x in items: if x <= pivot: less.append(x) else: greater.append(x) return quicksort(less) + [pivot] + quicksort(greater)