\ 4tH library - Radix sort LSB - Copyright 2022 J.L. Bezemer
\ You can redistribute this file and/or modify it under
\ the terms of the GNU General Public License

\ NOTE: This routine can ONLY be used to sort unsigned integers!

[UNDEFINED] sort      [IF]
[UNDEFINED] precedes  [IF] defer precedes         [THEN]
[UNDEFINED] (digit)   [IF] 65536 constant (digit) [THEN]
                                       \ 2, 4, 16, 256 or 65536
: (compare)                            ( f n a1 a2 -- f n)
  ?do
    i cell+ @ over and over i @ and precedes
    if i cell+ @ i @ i cell+ ! i ! >r >zero r> then
  2 cells +loop
;

: sort                                 ( a n -- )
  dup 2 < if 2drop ;then 2>r (digit) 1-
  begin
    dup
  while
    begin
      true swap 2r@ 1- bounds cell+ (compare) 2r@ 1- bounds (compare) swap
    until (digit) *
  repeat drop 2rdrop
;

[DEFINED] 4TH# [IF]
  hide (compare)
  hide (digit)
[THEN]
[THEN]

