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