Advertisement
George_Zagorsky_1

Time compl QuickSort, Insertion Sort, Bubble Sort

May 30th, 2023
638
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | Legal | 0 0
  1. from datetime import datetime
  2.  
  3.  
  4. def quick_sort(arr):
  5.     if len(arr) < 2:
  6.         return arr
  7.     el = arr[len(arr) // 3]
  8.     left = [x for x in arr if x < el]
  9.     mid = [x for x in arr if x == el]
  10.     right = [x for x in arr if x > el]
  11.     return quick_sort(left) + mid + quick_sort(right)
  12.  
  13.  
  14. def timer(function):
  15.     def wrapper(*args, **kwargs):
  16.         now = datetime.now()
  17.         res = function(*args, **kwargs)
  18.         print(f"time of func is {datetime.now() - now}")
  19.  
  20.     return wrapper
  21.  
  22.  
  23. @timer
  24. def bubble_sort(arr):
  25.     for i in range(len(arr)):
  26.         for j in range(len(arr) - 1):
  27.             if arr[j] > arr[j + 1]:
  28.                 arr[j], arr[j + 1] = arr[j + 1], arr[j]
  29.     return arr
  30.  
  31. @timer
  32. def insertion_sort(arr):
  33.     for i in range(len(arr) - 1):
  34.         j = i + 1
  35.         while j > -1 and arr[j - 1] > arr[j]:
  36.             arr[j - 1], arr[j] = arr[j], arr[j - 1]
  37.             j -= 1
  38.  
  39.     return arr
  40.  
  41. arr = [1, 5, 2, 3, 4, 6, 2, 1] * 1000
  42. # j, j + 1
  43. print(bubble_sort(arr))
  44. now = datetime.now()
  45. quick_sort(arr)
  46. print(f"time of func {datetime.now() - now}")
  47. print(insertion_sort(arr))
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement