Sorting algorithms/Comb sort: Difference between revisions

m
(Added solution for Action!)
Line 1,439:
This version is an academic demonstration that aligns with the algorithm. As is, it is limited to use one static array and sorts in ascending order only.
<lang forth>\ combsort for the Forth Newbie (GForth)
 
HEX
\ gratuitous variables ( Addfor clarity but NOT re-entrant)
VARIABLE0 VALUE GAP
VARIABLE SORTED \ flag
 
DECIMAL
Line 1,449 ⟶ 1,448:
 
\ allocate a small array of cells
CREATE Q SIZE 2+ CELLS ALLOT
 
\ operator to index into the array
Line 1,455 ⟶ 1,454:
 
\ fill array and see array
: INITDATA ( -- ) SIZE 0 DO SIZE I - I ]Q ! LOOP ;
: SEEDATA ( -- ) CR SIZE 0 DO I ]Q @ U. LOOP ;
 
: SEEDATA ( -- ) CR SIZE 0 DO I ]Q @ U. LOOP ;
 
\ computedivide aby new gap1.35 using scaledForth's scaling divisionoperator
\ factored out forfound this example.ratio Couldto be a macro or inlinethe code.fastest
: /1.335/ ( n -- n' ) 100 10 13135 */ ;
 
: XCHG ( adr1 adr2 n1 n2-- ) OVER @ OVER @ SWAP ROT ! SWAP ! ;
\ factored out for this example. Could be a macro or inline code.
: XCHG ( adr1 adr2 n1 n2-- ) SWAP ROT ! SWAP ! ;
 
: COMBSORT ( n -- )
DUP >R TO GAP \ copyset nGAP to return stackn
1+ GAP ! \ set GAP to n+1
BEGIN
GAP @ /1.335/ TO GAP ! \ re-compute the gap
SORTED ON
R@DUP GAP( @-- n) GAP - 0 \ n-gap is loop limit
DO
I GAP @ + ]Q @ I ]Q @ \ compute array addresses<
OVER @ OVER @ \ fetch the data in each cell
2DUP < \ compare a copy of the data
IF
XCHG I GAP + ]Q I ]Q XCHG \ Exchange the data in the cells
SORTED OFF \ flag we are not sorted
ELSE
2DROP 2DROP \ remove address and data
THEN
LOOP
SORTED @ GAP @ 0= AND \ test for complete
UNTIL
DROP
R> DROP ; \ remove 'n' from return stack </lang>
;
 
=={{header|Fortran}}==
Anonymous user