-
-
Notifications
You must be signed in to change notification settings - Fork 50.5k
Expand file tree
/
Copy pathrandomized_quicksort.py
More file actions
33 lines (25 loc) · 768 Bytes
/
randomized_quicksort.py
File metadata and controls
33 lines (25 loc) · 768 Bytes
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
import random
from typing import List
def randomized_quicksort(arr: List[int]) -> List[int]:
"""
Sorts a list of integers using randomized QuickSort algorithm.
Args:
arr (List[int]): List of integers to sort.
Returns:
List[int]: Sorted list of integers.
Examples:
>>> randomized_quicksort([3, 6, 1, 8, 4])
[1, 3, 4, 6, 8]
>>> randomized_quicksort([])
[]
"""
if len(arr) <= 1:
return arr
pivot = random.choice(arr)
less = [x for x in arr if x < pivot]
equal = [x for x in arr if x == pivot]
greater = [x for x in arr if x > pivot]
return randomized_quicksort(less) + equal + randomized_quicksort(greater)
if __name__ == "__main__":
import doctest
doctest.testmod()