Sorting algorithms/Bubble sort: Difference between revisions

Content added Content deleted
Line 124: Line 124:
==[[Forth]]==
==[[Forth]]==
[[Category:Forth]]
[[Category:Forth]]
Sorts the 'cnt' cells stored at 'addr'. Uses forth local variables for clarity.
Sorts the 'cnt' cells stored at 'addr' using the test stored in the deferred word 'bubble-test'. Uses forth local variables for clarity.


defer bubble-test
' > is bubble-test
: bubble { addr cnt -- }
: bubble { addr cnt -- }
cnt 1 DO
cnt 1 do
addr cnt i - cells bounds DO
addr cnt i - cells bounds do
i 2@ > if i 2@ swap i 2! then
i 2@ bubble-test if i 2@ swap i 2! then
cell +LOOP
cell +loop
LOOP ;
loop ;


This is the same algorithm done without the local variables:
This is the same algorithm done without the local variables:


: bubble ( addr cnt -- )
: bubble ( addr cnt -- )
dup 1 DO
dup 1 do
2dup i - cells bounds DO
2dup i - cells bounds do
i 2@ > if i 2@ swap i 2! then
i 2@ bubble-test if i 2@ swap i 2! then
cell +LOOP
cell +loop
LOOP ;
loop ;

Test either version with this:
create test
8 , 1 , 4 , 2 , 10 , 3 , 7 , 9 , 6 , 5 ,
here test - cell / constant tcnt
test tcnt cells dump
' > is bubble-test
test tcnt bubble
test tcnt cells dump
' < is bubble-test
test tcnt bubble
test tcnt cells dump


==[[Haskell]]==
==[[Haskell]]==