Skip to content

Commit 1199825

Browse files
author
deepshekhardas
committed
fix: add input validation to cyclic_sort to prevent infinite loop
1 parent c0db072 commit 1199825

1 file changed

Lines changed: 8 additions & 0 deletions

File tree

sorts/cyclic_sort.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ def cyclic_sort(nums: list[int]) -> list[int]:
1919
2020
:param nums: List of n integers from 1 to n to be sorted.
2121
:return: The same list sorted in ascending order.
22+
:raises ValueError: If nums contains non-integer or negative values.
2223
2324
Time complexity: O(n), where n is the number of integers in the list.
2425
@@ -27,8 +28,15 @@ def cyclic_sort(nums: list[int]) -> list[int]:
2728
[]
2829
>>> cyclic_sort([3, 5, 2, 1, 4])
2930
[1, 2, 3, 4, 5]
31+
>>> cyclic_sort([3, 5, -2, 1, 4])
32+
Traceback (most recent call last):
33+
...
34+
ValueError: All values must be positive integers
3035
"""
3136

37+
if any(not isinstance(x, int) or x <= 0 for x in nums):
38+
raise ValueError("All values must be positive integers")
39+
3240
# Perform cyclic sort
3341
index = 0
3442
while index < len(nums):

0 commit comments

Comments
 (0)