I use Quicksort to sort integers that are elements in sets represented by entries on the stack. It works fine, except when it comes to sorting larger (about 10,000 items) sets that are already sorted.
: adswap \ ad1 ad2 --
over @ over @ swap rot ! swap ! ;
: singlepart \ ad1 ad2 -- ad
tuck 2dup @ locals| p ad | swap \ ad2 ad2 ad1
do i @ p < \ ad2 flag
if ad i adswap ad cell + to ad then cell \ ad2 cell
+loop ad adswap ad ; \ ad
: qsort \ ad1 ad2 -- pointing on first and last cell in array
2dup <
if 2dup singlepart >r
swap r@ cell - recurse
r> cell + swap recurse
else 2drop
then ;
Could this be an overflow on the return stack? It is almost impossible for the program to track when the array is sorted or not, so how to solve the problem?
source
share