/***************************************************************************************************************** SAS file name: sort_array.sas File location: __________________________________________________________________________________________________________________ Purpose: To demonstrate how to sort arrays in SAS with the Call Sortn and Sortc routines and the hash object. Also, I demonstrate how to implement the Quicksort algorithm with the flexible %qsort macro Author: Peter Clemmensen Creation Date: 17/01/2020 This program supports the blog post "4 Techniques To Sort An Array in SAS" on SASnrd.com *****************************************************************************************************************/ /* Proc Sort */ data have; array x {10} (8 10 4 7 2 5 1 9 3 6); do _N_ = 1 to dim (x); _x = x [_N_]; output; end; run; proc sort data=have; by _x; run; data want(drop=_:); array x {10}; do _N_ = 1 by 1 until (lr); set have(keep=_x) end=lr; x [_N_] = _x; end; run; /* Call Sortn */ data _null_; array x {10} (8 10 4 7 2 5 1 9 3 6); call sortn (of x[*]); put (x[*])(=); run; /* The hash object */ data _null_; array x {10} (8 10 4 7 2 5 1 9 3 6); declare hash h (multidata : "Y", ordered : "A"); /* 1 */ h.definekey ("_x"); h.definedone(); declare hiter hi ("h"); do _N_ = lbound(x) to hbound(x); /* 2 */ _x = x[_N_]; rc = h.add(); end; put (x[*])(=); do _N_ = lbound(x) to hbound(x); /* 3 */ hi.next(); x[_N_] = _x; end; put (x[*])(=); run; /* The Quicksort Algorithm Macro */ /* Sort a simple array */ data _null_; array x {10} (8 10 4 7 2 5 1 9 3 6); %qsort (Arr=x); put (x[*])(=); run; /* Sort two parallel arrays */ data _null_; array x {10} (8 10 4 7 2 5 1 9 3 6); array y {10} (3 1 7 4 9 6 10 2 8 5); %qsort (Arr=x y, By=x); put (x[*])(=); put (y[*])(=); run; /* Sort the first five elements of the array */ data _null_; array x {10} (8 10 4 7 2 5 1 9 3 6); %qsort (Arr=x, lb=1, hb=5); put (x[*])(=); run;