snippetMinor
In place quicksort
Viewed 0 times
placequicksortstackoverflow
Problem
I implemented my own sorting in VBA because it doesn't provide its own, and it's healthy to test yourself. It was surprisingly difficult and I ended up make a few tweaks that I didn't expect to make in order for it to sort.
Public Sub quicksort(ByRef arr As Variant, _
ByVal left As Integer, _
ByVal right As Integer)
If right = p And l r Then Call swap(arr(l), arr(r))
Wend
' Don't swap the same thing
If l <> right Then Call swap(arr(right), arr(l))
Call quicksort(arr, left, l - 1)
Call quicksort(arr, l + 1, right)
End SubSolution
Few notes.
- All algorithms on ranges are much simpler if the range is considered semi-open (that is,
rightis just beyond the last interesting element.
- The `While l
- One more thing you want to do is to eliminate a last tail-recursive call to quicksort. It is very well possible that the compiler will do it for you; still it is better to be explicit.
Context
StackExchange Code Review Q#47591, answer score: 7
Revisions (0)
No revisions yet.