Skip to content

Instantly share code, notes, and snippets.

@kom-bu
Created June 19, 2020 02:55
Show Gist options
  • Save kom-bu/720d444fbf86ce3fcdf397ab1e4cacfb to your computer and use it in GitHub Desktop.
Save kom-bu/720d444fbf86ce3fcdf397ab1e4cacfb to your computer and use it in GitHub Desktop.
Counting sort
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"def c_sorted(a, ubound, key=lambda x: x):\n",
" counter = [0] * ubound\n",
" for ai in a:\n",
" counter[key(ai)] += 1\n",
" for i in range(1, ubound):\n",
" counter[i] += counter[i - 1]\n",
" b = [0] * len(a)\n",
" for ai in reversed(a):\n",
" counter[key(ai)] -= 1\n",
" b[counter[key(ai)]] = ai\n",
" return b"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[2, 2, 3, 5, 8]"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"c_sorted([2,5,3,8,2], 10)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(2, 'a'), (2, 'e'), (3, 'c'), (5, 'b'), (8, 'd')]"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"c_sorted([(2, 'a'), (5, 'b'), (3, 'c'), (8, 'd'), (2, 'e')], 10, lambda x: x[0])"
]
},
{
"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.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment