fork download
  1. import random
  2. import time
  3. import matplotlib.pyplot as plt
  4.  
  5. def quick_sort(arr):
  6. if len(arr) <= 1:
  7. return arr
  8.  
  9. pivot = arr[len(arr) // 2] # Corrected pivot selection
  10. left = [x for x in arr if x < pivot]
  11. middle = [x for x in arr if x == pivot] # Fixed middle part
  12. right = [x for x in arr if x > pivot]
  13.  
  14. return quick_sort(left) + middle + quick_sort(right) # Corrected recursive calls
  15.  
  16. def measure_sort_time(n):
  17. arr = [random.randint(1, 10000) for _ in range(n)] # Fixed random number generation
  18. start_time = time.time()
  19. quick_sort(arr)
  20. end_time = time.time()
  21. return end_time - start_time # Fixed subtraction syntax
  22.  
  23. sizes = []
  24. times = []
  25.  
  26. for n in range(10, 10001, 500): # Fixed range syntax
  27. sizes.append(n)
  28. times.append(measure_sort_time(n))
  29.  
  30. plt.plot(sizes, times, marker='o') # Fixed syntax errors
  31. plt.title("Quick Sort: Time taken vs Number of Elements")
  32. plt.xlabel("Number of Elements") # Added x-axis label
  33. plt.ylabel("Time (seconds)")
  34. plt.grid(True) # Added y-axis label
  35. plt.show() # Added plt.show() to display the plot
Success #stdin #stdout 1.27s 55472KB
stdin
Standard input is empty
stdout
Standard output is empty