Forth quicksort issues for large sorted arrays

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?

+4
source share
1 answer

, Quicksort, , . : . , :

, O (log n), , .

, .

qsort:

: qsort \ ad1 ad2 --      pointing on first and last cell in array
  begin
    2dup < 0= if 2drop exit then
    2dup - negate 1 rshift >r \ keep radius (half of the distance)
    2dup singlepart 2dup - >r >r \ ( R: radius distance2 ad )
    r@ cell - swap r> cell+ swap \ ( d-subarray1 d-subarray2 )
    2r> u< if 2swap then recurse \ take smallest subarray first
  again \ tail call optimization by hand
;
+4

Source: https://habr.com/ru/post/1651706/


All Articles