111 lines
2.6 KiB
Plaintext
111 lines
2.6 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"# Radix Sort\n",
|
|
"© 2021, Joe James"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 21,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# flatten into a 1D List\n",
|
|
"from functools import reduce\n",
|
|
"def flatten(A):\n",
|
|
" return reduce(lambda x, y: x + y, A)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 34,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def radix_sort(A):\n",
|
|
" # get number of digits in largest item\n",
|
|
" num_digits = len(str(max(A)))\n",
|
|
" for digit in range(0, num_digits):\n",
|
|
" B = [[] for i in range(10)]\n",
|
|
" e = 10 ** digit\n",
|
|
" for item in A:\n",
|
|
" # num is the bucket number that the item will be put into\n",
|
|
" num = item // e % 10\n",
|
|
" B[num].append(item)\n",
|
|
" A = flatten(B)\n",
|
|
" return A"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### Test Function\n",
|
|
"Set a result flag. The j loop is used to perform 1000 test iterations. The next two lines create and shuffle list A of 100 integers. Then A is passed to our sorting function. The sorted result is compared to a sort using Python's sorted function. After 1000 iterations of the test, the result is printed. \n",
|
|
"Note that Radix is not in-place, so we need to assign the returned list to A, A = func(A)\n",
|
|
"\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 35,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Success\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"import random\n",
|
|
"\n",
|
|
"def test(func):\n",
|
|
" result = 'Success'\n",
|
|
" for j in range(1000):\n",
|
|
" A = [k for k in range(100)]\n",
|
|
" random.shuffle(A)\n",
|
|
" A = func(A)\n",
|
|
" if A != sorted(A):\n",
|
|
" result = 'Failed'\n",
|
|
" print(result)\n",
|
|
"test(radix_sort)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": []
|
|
}
|
|
],
|
|
"metadata": {
|
|
"kernelspec": {
|
|
"display_name": "Python 3",
|
|
"language": "python",
|
|
"name": "python3"
|
|
},
|
|
"language_info": {
|
|
"codemirror_mode": {
|
|
"name": "ipython",
|
|
"version": 3
|
|
},
|
|
"file_extension": ".py",
|
|
"mimetype": "text/x-python",
|
|
"name": "python",
|
|
"nbconvert_exporter": "python",
|
|
"pygments_lexer": "ipython3",
|
|
"version": "3.7.0"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 2
|
|
}
|