Sorting algorithms/Comb sort: Difference between revisions
Content added Content deleted
(Added solution for Action!) |
|||
Line 1,439: | 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. |
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) |
<lang forth>\ combsort for the Forth Newbie (GForth) |
||
HEX |
HEX |
||
\ gratuitous variables |
\ gratuitous variables for clarity |
||
0 VALUE GAP |
|||
VARIABLE SORTED |
VARIABLE SORTED |
||
DECIMAL |
DECIMAL |
||
Line 1,449: | Line 1,448: | ||
\ allocate a small array of cells |
\ allocate a small array of cells |
||
CREATE Q SIZE CELLS ALLOT |
CREATE Q SIZE 2+ CELLS ALLOT |
||
\ operator to index into the array |
\ operator to index into the array |
||
Line 1,455: | Line 1,454: | ||
\ fill array and see array |
\ fill array and see array |
||
: INITDATA ( -- ) SIZE 0 DO |
: INITDATA ( -- ) SIZE 0 DO SIZE I - I ]Q ! LOOP ; |
||
⚫ | |||
⚫ | |||
\ |
\ divide by 1.35 using Forth's scaling operator |
||
\ |
\ found this ratio to be the fastest |
||
: |
: 1.35/ ( n -- n' ) 100 135 */ ; |
||
⚫ | |||
\ factored out for this example. Could be a macro or inline code. |
|||
⚫ | |||
: COMBSORT ( n -- ) |
: COMBSORT ( n -- ) |
||
DUP |
DUP TO GAP \ set GAP to n |
||
1+ GAP ! \ set GAP to n+1 |
|||
BEGIN |
BEGIN |
||
GAP |
GAP 1.35/ TO GAP \ re-compute the gap |
||
SORTED ON |
SORTED ON |
||
DUP ( -- n) GAP - 0 \ n-gap is loop limit |
|||
DO |
DO |
||
I GAP |
I GAP + ]Q @ I ]Q @ < |
||
OVER @ OVER @ \ fetch the data in each cell |
|||
2DUP < \ compare a copy of the data |
|||
IF |
IF |
||
I GAP + ]Q I ]Q XCHG \ Exchange the data in the cells |
|||
SORTED OFF \ flag we are not sorted |
SORTED OFF \ flag we are not sorted |
||
ELSE |
|||
2DROP 2DROP \ remove address and data |
|||
THEN |
THEN |
||
LOOP |
LOOP |
||
SORTED @ GAP |
SORTED @ GAP 0= AND \ test for complete |
||
UNTIL |
UNTIL |
||
DROP |
|||
R> DROP ; \ remove 'n' from return stack </lang> |
|||
; |
|||
=={{header|Fortran}}== |
=={{header|Fortran}}== |