1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
| import random
def selection_sort(nums): if len(nums) == 0: return [] n = len(nums) for i in range(n): for j in range(i+1,n): if nums[j] < nums[i]: nums[i], nums[j] = nums[j], nums[i] return nums
def bubble_sort(nums): n = len(nums) if n <= 1: return nums for i in range(n): for j in range(0, n-i-1): if nums[j] > nums[j+1]: nums[j], nums[j+1] = nums[j+1], nums[j] return nums
def insersion_sort(nums): n = len(nums) if n <= 1: return nums for i in range(1,n): key = nums[i] j = i-1 while j >= 0 and key <= nums[j]: nums[j+1] = nums[j] j -= 1 nums[j+1] = key return nums
def heapify(arr, n ,i): l = 2*i + 1 r = 2*i + 2
largest = i if l < n and nums[largest] < nums[l]: largest = l if r < n and nums[largest] < nums[r]: largest = r if largest != i: nums[largest], nums[i] = nums[i], nums[largest] heapify(arr, n, largest)
def heap_sort(arr): n = len(arr) for i in range(n//2, -1, -1): heapify(arr, n, i) for i in range(n-1, 0, -1): arr[0], arr[i] = arr[i], arr[0] heapify(arr, i, 0) return nums
def merge_sort(arr): n = len(arr) if n > 1: mid = n//2 left = arr[:mid] right = arr[mid:] left = merge_sort(left) right = merge_sort(right) i = j = k = 0 while i < len(left) and j < len(right) : if left[i] < right[j]: arr[k] = left[i] i += 1 else: arr[k] = right[j] j += 1 k += 1 if i < len(left): arr[k] = left[i] k += 1 if j < len(right): arr[k] = right[j] j += 1 return arr
def partition(nums, l, r): pivot = nums[r] i = l for j in range(l, r): if nums[j] <= pivot: nums[i], nums[j] = nums[j], nums[i] i += 1 nums[i], nums[r] = nums[r], nums[i] return i
def random_parition(nums, l, r): if l >= r: return pivot = random.randint(l, r) nums[pivot], nums[r] = nums[r], nums[pivot] return partition(nums, l, r) def quick_sort(nums, l, r): if l >= r: return pivot = random_parition(nums, l, r) quick_sort(nums,l, pivot-1) quick_sort(nums,pivot+1, r) nums_list = [ [], [2,1,3,4,5,6], [1,2,3,4,5,6], [6,5,4,3,2,1], [6,3,4,7,8,1]]
for nums in nums_list: print(selection_sort(nums))
for nums in nums_list: print(bubble_sort(nums))
print("heap_sort") for nums in nums_list: print(heap_sort(nums))
print("merge sort") for nums in nums_list: print(merge_sort(nums))
print("quick sort") for nums in nums_list: quick_sort(nums, 0, len(nums)-1) print(nums)
|