Skip to content

Commit 866f42b

Browse files
committed
error handling
1 parent a124066 commit 866f42b

File tree

1 file changed

+12
-25
lines changed

1 file changed

+12
-25
lines changed

pydatastructs/linear_data_structures/algorithms.py

Lines changed: 12 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1889,54 +1889,41 @@ def radix_sort(array, comp=lambda u, v: u <= v, **kwargs):
18891889
for sorting. Optional, by default, less than or
18901890
equal to is used for comparing two
18911891
values.
1892-
1893-
Examples
1894-
========
1895-
>>> from pydatastructs import OneDimensionalArray, radix_sort
1896-
>>> arr = OneDimensionalArray(int,[170, 45, 75, 90, 802, 24, 2, 66])
1897-
>>> radix_sort(arr)
1898-
>>> [arr[0], arr[1], arr[2], arr[3], arr[4], arr[5], arr[6], arr[7]]
1899-
[2, 24, 45, 66, 75, 90, 170, 802]
1900-
1901-
References
1902-
==========
1903-
.. [1] https://en.wikipedia.org/wiki/Radix_sort
19041892
"""
19051893
# Raise error if not Python backend
19061894
raise_if_backend_is_not_python(radix_sort, kwargs.get('backend', Backend.PYTHON))
19071895

19081896
start = kwargs.get('start', 0)
19091897
end = kwargs.get('end', len(array) - 1)
19101898

1899+
# Create a sub_array excluding None values, and track positions of None values
19111900
sub_array = []
1901+
none_indices = []
19121902
max_val = 0
1913-
none_indices = [] # To track positions of None values
1914-
for i in range(0, len(array)):
1903+
1904+
for i in range(start, end + 1):
19151905
if array[i] is not None:
19161906
sub_array.append(array[i])
1917-
if array[i] > max_val:
1918-
max_val = array[i]
1907+
max_val = max(max_val, array[i])
19191908
else:
1920-
none_indices.append(i) # Track the index of None values
1909+
none_indices.append(i) # Track positions of None
19211910

19221911
# Perform counting sort on the sub_array (without None values)
19231912
exp = 1
19241913
while max_val // exp > 0:
19251914
_count_sort_for_radix(sub_array, exp, comp)
19261915
exp *= 10
19271916

1928-
# Reintroduce None values at their original positions
1917+
# Insert None values back at their respective positions
1918+
sorted_array = sub_array[:]
19291919
for idx in none_indices:
1930-
sub_array.insert(idx, None)
1920+
sorted_array.insert(idx - start, None) # Insert None back at the correct position
19311921

1932-
# Slice sub_array to ensure we only modify the desired range (start to end)
1933-
sub_array = sub_array[start:end + 1]
1934-
1935-
# Ensure the final array is updated correctly with sorted values
1922+
# Update the original array with the sorted values
19361923
for i in range(start, end + 1):
1937-
array[i] = sub_array[i - start]
1924+
array[i] = sorted_array[i - start]
19381925

19391926
if _check_type(array, (DynamicArray, _arrays.DynamicOneDimensionalArray)):
19401927
array._modify(True)
1941-
1928+
19421929
return array

0 commit comments

Comments
 (0)