Merge pull request #67 from donnemartin/develop

Polish quicksort challenge and solution
This commit is contained in:
Donne Martin 2016-06-18 22:17:40 -04:00 committed by GitHub
commit b470c821b4
2 changed files with 12 additions and 7 deletions

View File

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

View File

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