Untitled
unknown
python
a year ago
1.9 kB
5
Indexable
Never
from random import randint def pivot(arr): elem = arr[randint(0,len(arr)-1)] left = list(filter(lambda x:x<elem,arr)) center = [i for i in arr if i == elem] right = list(filter(lambda x:x>elem,arr)) return left,center,right def quicksort(arr): if len(arr)<=1: return arr left,center,right = pivot(arr) return quicksort(left)+center+quicksort(right) arr=[] for i in range(100): arr.append(randint(0,100)) print(quicksort(arr)) ###################################################################### def heapify(arr, n, i): largest = i l = 2 * i + 1 r = 2 * i + 2 if l < n and arr[i] < arr[l]: largest = l if r < n and arr[largest] < arr[r]: largest = r if largest != i: arr[i], arr[largest] = arr[largest], arr[i] heapify(arr, n, largest) def heapsort(arr): n = len(arr) for i in range(n // 2 - 1, -1, -1): heapify(arr, n, i) for i in range(n - 1, 0, -1): arr[i], arr[0] = arr[0], arr[i] heapify(arr, i, 0) return arr print(heapsort([1,0,3,2,5,4,6,3])) ################################################################################ def merge(left, right): result = [] i = j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result += left[i:] result += right[j:] return result def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left = arr[:mid] right = arr[mid:] left = merge_sort(left) right = merge_sort(right) return merge(left, right) print(merge_sort([1,0,3,2,5,4,6,3])) #############################################################