

CS 3100 Handout on Managing the stack when doing Quick Sort


Doing a recursive quick sort that manages the runtime stack:

Procedure Qsort (lo, hi) ;
begin
    (* this loop is used to eliminate the second recursive call *)
    (* this algorithm keeps the runtime stack limited to size O(logN) *)
  while (hi > lo) do 
  begin
    Partition (lo, hi, splitPoint) ;
    if    (hi-splitPoint) > (splitPoint-lo)
    then  begin
            Qsort (lo, splitPoint) ; (* do the small problem *) 
            lo := splitPoint 
          end
    else begin
           Qsort(splitPoint, hi) ;  (* do the small problem *) 
           hi := splitPoint
         end 
  end
end ;


Doing a non-recursive quick sort that manages the "save-stack":

Push ({1, n}) ;
repeat
  Pop ({lo,hi}) ;
  while lo < hi
  begin
    Partition (lo, hi, splitPoint) ;
    if    (hi-splitPoint) > (splitPoint-lo)
    then begin
           Push({splitPoint, hi}) ; (* put the big problem on the stack *)
           hi := splitPoint (* go to work on the small problem  *)
         end
    else begin
           Push({lo,splitPoint}) ; (* put the big problem on the stack *)
           lo := splitPoint (* go to work on the small problem  *)
         end 
  end ; (* while *)
until stack is empty
