From 7b51ec6487bb33696888fe8911f69df826342c00 Mon Sep 17 00:00:00 2001 From: Kaustubh J Date: Mon, 22 Apr 2019 02:46:14 +0530 Subject: [PATCH] Update index.md (#32513) Added python code and mentioned randomized pivot --- .../sorting-algorithms/quick-sort/index.md | 33 ++++++++++++++++--- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/guide/english/algorithms/sorting-algorithms/quick-sort/index.md b/guide/english/algorithms/sorting-algorithms/quick-sort/index.md index 23df4cc31f..83c9894c64 100644 --- a/guide/english/algorithms/sorting-algorithms/quick-sort/index.md +++ b/guide/english/algorithms/sorting-algorithms/quick-sort/index.md @@ -12,7 +12,7 @@ The steps involved in Quick Sort are: ## Exmaple Implementations in Various Languages -### A Quick-Sort Implementation in JavaScript: +### Implementation in JavaScript: ```javascript const arr = [6, 2, 5, 3, 8, 7, 1, 4] @@ -75,7 +75,7 @@ quickSort(arr, 0, arr.length - 1) console.log(arr) ``` -### A Quick-Sort Implementation in C +### Implementation in C ```C #include void swap(int* a, int* b) @@ -132,7 +132,31 @@ int main() } ``` -### A Quick-Sort Implementation in MATLAB +### Implementation in Python3 +```python +import random + +z=[random.randint(0,100) for i in range(0,20)] + +def quicksort(z): + if(len(z)>1): + piv=int(len(z)/2) + val=z[piv] + lft=[i for i in z if ival] + + res=quicksort(lft)+mid+quicksort(rgt) + return res + else: + return z + +ans1=quicksort(z) +print(ans1) + +``` + +### Implementation in MATLAB ```matlab a = [9,4,7,3,8,5,1,6,2]; @@ -163,7 +187,8 @@ end ``` -The space complexity of quick sort is O(n). This is an improvement over other divide and conquer sorting algorithms, which take O(nlong(n)) space. Quick sort achieves this by changing the order of elements within the given array. Compare this with the merge sort algorithm which creates 2 arrays, each length n/2, in each function call. +The space complexity of quick sort is `O(n)`. This is an improvement over other divide and conquer sorting algorithms, which take `O(nlong(n))` space. Quick sort achieves this by changing the order of elements within the given array. Compare this with the merge sort algorithm which creates 2 arrays, each length `n/2`, in each function call. +However there does exist the problem of this sorting algorithm being of time `O(n*n)` if the pivot is always kept at the middle. This can be overcomed by utilizing a random pivot ## Complexity