Polish quicksort challenge and solution

Update constraints and code.
This commit is contained in:
Donne Martin 2016-06-18 22:17:09 -04:00
parent 31359896a8
commit 981f775d97
2 changed files with 12 additions and 7 deletions

View File

@ -35,6 +35,8 @@
"## Constraints\n",
"\n",
"* Is a naiive solution sufficient (ie not in-place)?\n",
" * Yes\n",
"* Are duplicates allowed?\n",
" * Yes"
]
},
@ -162,7 +164,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.4.3"
"version": "3.5.0"
}
},
"nbformat": 4,

View File

@ -35,6 +35,8 @@
"## Constraints\n",
"\n",
"* Is a naiive solution sufficient (ie not in-place)?\n",
" * Yes\n",
"* Are duplicates allowed?\n",
" * Yes"
]
},
@ -96,16 +98,17 @@
"def quick_sort(data):\n",
" if data is None or len(data) < 2:\n",
" return data\n",
" equal = []\n",
" left = []\n",
" right = []\n",
" pivot_index = len(data) // 2\n",
" pivot_value = data[pivot_index]\n",
"\n",
" # Build the left and right partitions\n",
" for i in range(0, len(data)):\n",
" if i == pivot_index:\n",
" continue\n",
" if data[i] < pivot_value:\n",
" for i in range(len(data)):\n",
" if data[i] == pivot_value:\n",
" equal.append(data[i])\n",
" elif data[i] < pivot_value:\n",
" left.append(data[i])\n",
" else:\n",
" right.append(data[i])\n",
@ -113,7 +116,7 @@
" # Recursively apply quick_sort\n",
" left = quick_sort(left)\n",
" right = quick_sort(right)\n",
" return left + [pivot_value] + right"
" return left + equal + right"
]
},
{
@ -219,7 +222,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.4.3"
"version": "3.5.0"
}
},
"nbformat": 4,