@@ -1925,3 +1925,99 @@ def shell_sort(array, **kwargs):
19251925 array ._modify (True )
19261926
19271927 return array
1928+
1929+ def radix_sort (array , ** kwargs ):
1930+ """
1931+ Implements radix sort algorithm for non-negative integers.
1932+
1933+ Parameters
1934+ ==========
1935+
1936+ array: Array
1937+ The array which is to be sorted. Must contain non-negative integers.
1938+ start: int
1939+ The starting index of the portion
1940+ which is to be sorted.
1941+ Optional, by default 0
1942+ end: int
1943+ The ending index of the portion which
1944+ is to be sorted.
1945+ Optional, by default the index
1946+ of the last position filled.
1947+ comp: lambda/function
1948+ The comparator which is to be used
1949+ for sorting. If the function returns
1950+ False then only swapping is performed.
1951+ Optional, by default, less than or
1952+ equal to is used for comparing two
1953+ values.
1954+ backend: pydatastructs.Backend
1955+ The backend to be used.
1956+ Optional, by default, the best available
1957+ backend is used.
1958+
1959+ Returns
1960+ =======
1961+
1962+ output: Array
1963+ The sorted array.
1964+
1965+ Examples
1966+ ========
1967+
1968+ >>> from pydatastructs.linear_data_structures.algorithms import OneDimensionalArray, radix_sort
1969+ >>> arr = OneDimensionalArray(int, [170, 45, 75, 90, 802, 24, 2, 66])
1970+ >>> out = radix_sort(arr)
1971+ >>> str(out)
1972+ '[2, 24, 45, 66, 75, 90, 170, 802]'
1973+
1974+ References
1975+ ==========
1976+
1977+ .. [1] https://en.wikipedia.org/wiki/Radix_sort
1978+ """
1979+ backend = kwargs .pop ("backend" , Backend .PYTHON )
1980+ if backend == Backend .CPP :
1981+ return _algorithms .radix_sort (array , ** kwargs )
1982+ start = int (kwargs .get ('start' , 0 ))
1983+ end = int (kwargs .get ('end' , len (array ) - 1 ))
1984+
1985+ if start >= end :
1986+ return array
1987+
1988+ n = end - start + 1
1989+ if n <= 0 :
1990+ return array
1991+
1992+ max_val = array [start ]
1993+ for i in range (start + 1 , end + 1 ):
1994+ if array [i ] > max_val :
1995+ max_val = array [i ]
1996+ if max_val < 0 :
1997+ raise ValueError ("Radix sort requires non-negative integers" )
1998+
1999+ exp = 1
2000+ while max_val // exp > 0 :
2001+ count = [0 ] * 10
2002+ output = [0 ] * n
2003+ for i in range (start , end + 1 ):
2004+ digit = (array [i ] // exp ) % 10
2005+ count [digit ] += 1
2006+
2007+ for i in range (1 , 10 ):
2008+ count [i ] += count [i - 1 ]
2009+
2010+ for i in range (end , start - 1 , - 1 ):
2011+ digit = (array [i ] // exp ) % 10
2012+ count [digit ] -= 1
2013+ output [count [digit ]] = array [i ]
2014+
2015+ for i in range (n ):
2016+ array [start + i ] = output [i ]
2017+
2018+ exp *= 10
2019+
2020+ if _check_type (array , (DynamicArray , _arrays .DynamicOneDimensionalArray )):
2021+ array ._modify (True )
2022+
2023+ return array
0 commit comments