Understanding Quick Sort Algorithm
carpet92 opened this issue · comments
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):
function quicksort(array) {
if (array.length < 2) {
// base case, arrays with 0 or 1 element are already "sorted"
return array
} else {
// recursive case
let pivot = array[0]
// sub-array of all the elements less than the pivot
let less = array.slice(1).filter(function(el) {
return el <= pivot
})
// sub-array of all the elements greater than the pivot
let greater = array.slice(1).filter(function(el) {
return el > pivot
})
return quicksort(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 👇:
quicksort([5, 2, 3])
pivot = 5
less = [2, 3]
greater = []
quicksort([2, 3]).concat([5], quicksort([]))
and last step:
quicksort([2, 3])
pivot = 2
less = []
greater = [3]
quicksort([]).concat([2], quicksort([3]))
AND now the part I'm not sure I understand correctly:
now we concat array down to up i.e.:
[] + [2] + [3] + [5] + [10]
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:
quicksort([]).concat([2], quicksort([3]))
when quicksort function gets array [3]
:
quicksort([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?
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.
@oleg-gf hm. so, we have stack work from top to down. like on my last image?! thanks.
Yes, Last Input First Output.