write heap_sort_solution.ipynb

This commit is contained in:
Hyeongnam Jang 2018-11-29 09:03:42 +09:00
parent 50f7179f8c
commit 2525deb843

View File

@ -34,7 +34,7 @@
"source": [
"## Constraints\n",
"\n",
"* Is a naive solution sufficient (ie not in-place)?\n",
"* Is a naive solution sufficient?\n",
" * Yes\n",
"* Are duplicates allowed?\n",
" * Yes\n",
@ -63,31 +63,23 @@
"## Algorithm\n",
"\n",
"Wikipedia's animation:\n",
"![alt text](http://upload.wikimedia.org/wikipedia/commons/6/6a/Sorting_quicksort_anim.gif)\n",
"![alt text](https://upload.wikimedia.org/wikipedia/commons/1/1b/Sorting_heapsort_anim.gif)\n",
"\n",
"* Set pivot to the middle element in the data\n",
"* For each element:\n",
" * If current element is the pivot, continue\n",
" * If the element is less than the pivot, add to left array\n",
" * Else, add to right array\n",
"* Recursively apply quicksort to the left array\n",
"* Recursively apply quicksort to the right array\n",
"* Merge the left array + pivot + right array\n",
"* Convert a given list to a max-heap\n",
"* For i from n-1 to 0 (n is size of a given list) :\n",
" * Swap 0-th element with i-th element\n",
" * Heapfiy a sub-list(0 ~ i-1)\n",
"\n",
"Complexity:\n",
"* Time: O(n log(n)) average, best, O(n^2) worst\n",
"* Time: O(n log(n)) average, best, worst\n",
"* Space: O(n)\n",
" * This implementation is in-place sort, so it needs no additional space.\n",
"\n",
"Misc:\n",
"\n",
"* More sophisticated implementations are in-place, although they still take up recursion depth space\n",
"* Most implementations are not stable\n",
"\n",
"See [Quicksort on wikipedia](https://en.wikipedia.org/wiki/Quicksort):\n",
"\n",
"Typically, quicksort is significantly faster in practice than other Θ(nlogn) algorithms, because its inner loop can be efficiently implemented on most architectures [presumably because it has good cache locality], and in most real-world data, it is possible to make design choices which minimize the probability of requiring quadratic time.\n",
"\n",
"See: [Quicksort vs merge sort](http://stackoverflow.com/questions/70402/why-is-quicksort-better-than-mergesort)"
"See [Heapsort on wikipedia](https://en.wikipedia.org/wiki/Heapsort):\n"
]
},
{
@ -99,7 +91,7 @@
},
{
"cell_type": "code",
"execution_count": 2,
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
@ -148,7 +140,7 @@
},
{
"cell_type": "code",
"execution_count": 12,
"execution_count": 8,
"metadata": {},
"outputs": [
{
@ -196,7 +188,7 @@
},
{
"cell_type": "code",
"execution_count": 3,
"execution_count": 9,
"metadata": {},
"outputs": [
{