@@ -1850,3 +1850,65 @@ def partition(array, lower, upper):
18501850 intro_sort (array , start = p + 1 , end = upper , maxdepth = maxdepth - 1 , ins_threshold = ins_threshold )
18511851
18521852 return array
1853+
1854+ def _count_sort_for_radix (array , exp , comp ):
1855+ n = len (array )
1856+ output = [None ] * n
1857+ count = [0 ] * 10
1858+
1859+ for i in range (n ):
1860+ index = (array [i ] // exp ) % 10
1861+ count [index ] += 1
1862+
1863+ for i in range (1 , 10 ):
1864+ count [i ] += count [i - 1 ]
1865+
1866+ i = n - 1
1867+ while i >= 0 :
1868+ index = (array [i ] // exp ) % 10
1869+ output [count [index ] - 1 ] = array [i ]
1870+ count [index ] -= 1
1871+ i -= 1
1872+
1873+ for i in range (n ):
1874+ array [i ] = output [i ]
1875+
1876+ def radix_sort (array , comp = lambda u , v : u <= v , ** kwargs ):
1877+ """
1878+ Implements Radix Sort.
1879+
1880+ Parameters
1881+ ==========
1882+ array: Array
1883+ The array which is to be sorted.
1884+ comp: lambda/function
1885+ The comparator which is to be used
1886+ for sorting. Optional, by default, less than or
1887+ equal to is used for comparing two
1888+ values.
1889+
1890+ Examples
1891+ ========
1892+ >>> from pydatastructs import OneDimensionalArray, radix_sort
1893+ >>> arr = OneDimensionalArray(int,[170, 45, 75, 90, 802, 24, 2, 66])
1894+ >>> radix_sort(arr)
1895+ >>> [arr[0], arr[1], arr[2], arr[3], arr[4], arr[5], arr[6], arr[7]]
1896+ [2, 24, 45, 66, 75, 90, 170, 802]
1897+
1898+ References
1899+ ==========
1900+ .. [1] https://en.wikipedia.org/wiki/Radix_sort
1901+ """
1902+ # Raise error if not Python backend
1903+ raise_if_backend_is_not_python (radix_sort , kwargs .get ('backend' , Backend .PYTHON ))
1904+
1905+ # Get maximum number to determine number of digits
1906+ max_val = max (array )
1907+
1908+ exp = 1
1909+ while max_val // exp > 0 :
1910+ _count_sort_for_radix (array , exp , comp )
1911+ exp *= 10
1912+
1913+ if _check_type (array , (DynamicArray , _arrays .DynamicOneDimensionalArray )):
1914+ array ._modify (True )
0 commit comments