{
"cells": [
{
"cell_type": "markdown",
"id": "691a7094",
"metadata": {},
"source": [
"# Non-comparison sorting"
]
},
{
"cell_type": "markdown",
"id": "71a63be0",
"metadata": {},
"source": [
"## Counting sort\n",
"\n",
"* Be careful. not x is True when x is 0, not just when x is None.\n",
"* count must have length (max value + 1) not max value\n",
"* Be careful about arr and count and check the indices are matched up and in range\n",
"* You can extend this implementation to negative numbers by finding the min and the max and mapping the values into the positive range.\n",
"* Decrementing from the count array as you overwrite the input array is a little nicer than creating another counter integer.\n",
"* Counting sort with negative numbers take some additional care (https://stackoverflow.com/questions/40476521/using-counting-sort-with-negative-values-descending-order)"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "f28a0f8a",
"metadata": {},
"outputs": [],
"source": [
"def counting_sort(arr):\n",
" max_value = None\n",
" for i in range(len(arr)):\n",
" if max_value is None or arr[i] > max_value:\n",
" max_value = arr[i]\n",
"\n",
" count = [0]*(max_value + 1)\n",
"\n",
" # Be careful about arr and count\n",
" # and what i is an index to.\n",
" for i in range(len(arr)):\n",
" count[arr[i]] += 1\n",
"\n",
" k = 0\n",
" for i in range(len(count)):\n",
" while count[i] > 0:\n",
" arr[k] = i\n",
" count[i] -= 1\n",
" k += 1"
]
},
{
"cell_type": "markdown",
"id": "50fd323d",
"metadata": {},
"source": [
"The last part that converts the count array to the sorted array doesn't work if\n",
"\n",
"* The elements have associated data that we want to copy along with the key.\n",
"* The key (what we're sorting by) is not the same as the data (as in radix sort).\n",
"\n",
"An alternative for that last part that does work with radix sort is:\n",
"\n",
"```python\n",
"for i in range(1, len(count)):\n",
" count[i] += count[i-1]\n",
"\n",
"output[0]*len(arr)\n",
"# Don't forget to go in reverse\n",
"for i in range(len(arr)-1, -1, -1):\n",
" # count[arr[i]-1 gives the index of output not arr\n",
" output[count[arr[i]]-1] = arr[i]\n",
" count[arr[i]] -= 1\n",
"\n",
"for i in range(len(arr)):\n",
" arr[i] = output[i]\n",
"```"
]
},
{
"cell_type": "markdown",
"id": "884721c4",
"metadata": {},
"source": [
"## Bucket sort\n",
"\n",
"* arr.sort() is in-place. sorted(arr) returns sorted array but doesn't change arr.\n",
"* Best for uniformly sorted data\n",
"* Either no. of buckets is given or pick len(arr) buckets. If the latter, won't that mean 1 element in each bucket? No, because what element goes in each bucket depends on its value and we may get unlucky and only get very small values."
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "f2164edb",
"metadata": {},
"outputs": [],
"source": [
"def bucket_sort(arr, k):\n",
" buckets = []\n",
" for _ in range(k):\n",
" buckets.append([])\n",
"\n",
" max_value = max(arr)\n",
" for i in range(len(arr)):\n",
" j = int((arr[i] / max_value) * (k - 1))\n",
" buckets[j].append(arr[i])\n",
"\n",
" for j in range(len(buckets)):\n",
" buckets[j].sort()\n",
"\n",
" k = 0\n",
" for i in range(len(buckets)):\n",
" for j in range(len(buckets[i])):\n",
" arr[k] = buckets[i][j]\n",
" k += 1"
]
},
{
"cell_type": "markdown",
"id": "fe15dce7",
"metadata": {},
"source": [
"## Radix sort\n",
"\n",
"When you have a very large number in your array, you can't use counting sort, because of how large the array of counts would be. But you can still use radix sort.\n",
"\n",
"In radix sort, you find the largest number in the array and you determine the place of its largest digit (1s or 10s or 100s, etc). Then you sort the whole array by the digit of each number in the 1s place. Then you sort the whole array by the digit of each number in the 10s place. And so on until youâ€™ve sorted by the digit of each number in the place of the largest digit of the largest number in the array.\n",
"\n",
"For sorting, you have to use a stable array, because otherwise the work you did to sort by digits in lower places would be erased.\n",
"\n",
"Why not sort by the digits in the 1s place last? Then the array would not be sorted at the end.\\newline\n",
"\n",
"What stable sorting to use? A stable counting sort is one option. First, you populate the count array like in vanilla counting sort. Then, you replace the count array with the cumulative sum of the counts. The property of this array is that if $c_i \\ne 0$, then $c_i - 1$ gives you an index where you should place $a_i$ and $c_i - 2$ gives you another index and so on until $c_i = 0$.\n",
"\n",
"```\n",
"0 0 1 0 2 0\n",
"0 0 1 1 3 3\n",
"x x x x\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "8c469f1b",
"metadata": {},
"outputs": [],
"source": [
"def counting_sort(arr, place):\n",
" count = [0]*10\n",
" for i in range(len(arr)):\n",
" # Example:\n",
" # 1024 = (1*1000 + 0*100 + 2*10 + 4*1)\n",
" # 1024 // 100 = (1*100 + 0*1 + 0 + 0)\n",
" # (arr[i] // place) zeroes out the lower placeholders\n",
" # and makes the target placeholder the 1s place.\n",
" # We just need to get the coefficient on the 1s place.\n",
" # We can do that by taking the number mod 10.\n",
" digit = (arr[i] // place) % 10\n",
"\n",
" count[digit] += 1\n",
"\n",
" for i in range(1, len(count)):\n",
" count[i] += count[i-1]\n",
"\n",
" output = [0]*len(arr)\n",
" for i in range(len(arr)-1, -1, -1):\n",
" digit = (arr[i] // place) % 10\n",
" # remember the index of count is a digit\n",
" output[count[digit]-1] = arr[i]\n",
" count[digit] -= 1\n",
"\n",
" for i in range(len(output)):\n",
" arr[i] = output[i]\n",
"\n",
"def radix(arr):\n",
" # The max place across each number in the array\n",
" # is equal to the max place of the max number\n",
" # in the array.\n",
" m = max(arr)\n",
"\n",
" place = 1\n",
"\n",
" # Integer division divides and drops the remainder.\n",
" # Example:\n",
" # 1024 // 1 = 1024\n",
" # 1024 // 10 = 102\n",
" # 1024 // 100 = 10\n",
" # 1024 // 1000 = 1\n",
" # 1024 // 10000 = 0\n",
" while m // place != 0:\n",
" counting_sort(arr, place)\n",
" place *= 10"
]
}
],
"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.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}