From 981f775d97d516664b69f0795f987bc2ca540d0f Mon Sep 17 00:00:00 2001 From: Donne Martin Date: Sat, 18 Jun 2016 22:17:09 -0400 Subject: [PATCH] Polish quicksort challenge and solution Update constraints and code. --- .../quick_sort/quick_sort_challenge.ipynb | 4 +++- .../quick_sort/quick_sort_solution.ipynb | 15 +++++++++------ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/sorting_searching/quick_sort/quick_sort_challenge.ipynb b/sorting_searching/quick_sort/quick_sort_challenge.ipynb index cdd768d..7b317d1 100644 --- a/sorting_searching/quick_sort/quick_sort_challenge.ipynb +++ b/sorting_searching/quick_sort/quick_sort_challenge.ipynb @@ -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, diff --git a/sorting_searching/quick_sort/quick_sort_solution.ipynb b/sorting_searching/quick_sort/quick_sort_solution.ipynb index 3285119..c49db1c 100644 --- a/sorting_searching/quick_sort/quick_sort_solution.ipynb +++ b/sorting_searching/quick_sort/quick_sort_solution.ipynb @@ -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,