You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Thanks for this great work on algorithms book. I now understand many of concepts which seemed difficult to me but now I'm stuck on Quick Sort algorithm and I cannot fully understand how its work.
JavaScript Version of Code (from repository):
functionquicksort(array){if(array.length<2){// base case, arrays with 0 or 1 element are already "sorted"returnarray}else{// recursive caseletpivot=array[0]// sub-array of all the elements less than the pivotletless=array.slice(1).filter(function(el){returnel<=pivot})// sub-array of all the elements greater than the pivotletgreater=array.slice(1).filter(function(el){returnel>pivot})returnquicksort(less).concat([pivot],quicksort(greater))}}
How I understanding parts of work this algorithm:
console.log(quicksort([10, 5, 2, 3]))
first step:
quicksort([10, 5, 2, 3])
pivot = 10 // get first item from array[0]
less = [5, 2, 3] // list of all item less than pivot
greater = [] // no items greater than pivot
quicksort([5, 2, 3]).concat([10], quicksort([]))
now we save this step ☝️ in stack and adding new step to up of stack 👇:
I mean, the case { return array } happens after quicksort([]).concat([2], quicksort([3])), and we have [ 2, 3 ] and [5], [10] in stack that joined to [ 2, 3 ] when function does last return.
Thanks for this great work on algorithms book. I now understand many of concepts which seemed difficult to me but now I'm stuck on Quick Sort algorithm and I cannot fully understand how its work.
JavaScript Version of Code (from repository):
How I understanding parts of work this algorithm:
first step:
now we save this step ☝️ in stack and adding new step to up of stack 👇:
and last step:
AND now the part I'm not sure I understand correctly:
now we concat array down to up i.e.:
Why it's confusing for me? Because In "Recursion" chapter says that stack runs from up to down like on following screenshot:
also on last part:
when quicksort function gets array
[3]
:but since base case return true
if (array.length < 2) { return array }
we just return[3]
array and code stop working.What happens on this part?
Can anyone help me to understand where I made a mistake in my explanations? What am I wrong about?
The text was updated successfully, but these errors were encountered: