Advertisement
amu2002

quicksort

Nov 20th, 2023 (edited)
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.40 KB | None | 0 0
  1. import random
  2.  
  3. # Quick Sort (Deterministic)
  4. def quick_sort(arr):
  5.     if len(arr) <= 1:
  6.         return arr
  7.     pivot = arr[0]
  8.     left = [x for x in arr[1:] if x < pivot]
  9.     right = [x for x in arr[1:] if x >= pivot]
  10.     return quick_sort(left) + [pivot] + quick_sort(right)
  11.  
  12. # Quick Sort (Randomized)
  13. def randomized_quick_sort(arr):
  14.     if len(arr) <= 1:
  15.         return arr
  16.     pivot_idx = random.randint(0, len(arr) - 1)
  17.     pivot = arr[pivot_idx]
  18.     left = [x for i, x in enumerate(arr) if i != pivot_idx and x < pivot]
  19.     right = [x for i, x in enumerate(arr) if i != pivot_idx and x >= pivot]
  20.     return randomized_quick_sort(left) + [pivot] + randomized_quick_sort(right)
  21.  
  22. # Function to test the Quick Sort variants
  23. def test_quick_sort(arr):
  24.     sorted_arr_deterministic = quick_sort(arr.copy())
  25.     sorted_arr_randomized = randomized_quick_sort(arr.copy())
  26.     print("Original array:", arr)
  27.     print("Deterministic Quick Sort:", sorted_arr_deterministic)
  28.     print("Randomized Quick Sort:", sorted_arr_randomized)
  29.  
  30. if __name__ == "__main__":
  31.     arr = list(map(int, input("Enter the array elements separated by spaces: ").split()))
  32.     test_quick_sort(arr)
  33.  
  34. """ Enter the array elements separated by spaces: 5 3 8 6 1 9 2 7 4
  35.    Original array: [5, 3, 8, 6, 1, 9, 2, 7, 4]
  36.    Deterministic Quick Sort: [1, 2, 3, 4, 5, 6, 7, 8, 9]
  37.    Randomized Quick Sort: [1, 2, 3, 4, 5, 6, 7, 8, 9]  """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement