Skip to content

Instantly share code, notes, and snippets.

@bahmanm
Created January 4, 2025 04:22
Show Gist options
  • Save bahmanm/fad02050b0cf44a38f0960f64f571995 to your computer and use it in GitHub Desktop.
Save bahmanm/fad02050b0cf44a38f0960f64f571995 to your computer and use it in GitHub Desktop.
Bubble sort an ArrayList in bjForth
####################################################################################################
# Compares the elements at `i` and `j` in `list` and swaps them if necessary.
#####################################################################################################
: COMPARE-AND-SWAP ( list i j -- )
2DUP ( list i j i j )
5 PICK .< get(Integer)/1 >. ( list i j i e_j )
SWAP 5 PICK .< get(Integer)/1 >. ( list i j e_j e_i )
2DUP ( list i j e_j e_i e_j e_i )
> IF ( list i j e_j e_i )
3 PICK 6 PICK ( list i j e_j e_i j list )
.< set(Integer, Object)/2 >. DROP ( list i j e_j )
3 PICK 5 PICK ( list i j e_j i list )
.< set(Integer, Object)/2 >. DROP ( list i j )
ELSE
2DROP
THEN
2DROP DROP
;
####################################################################################################
# Bubble sorts (descendingly) a given list
####################################################################################################
: BUBBLE-SORT ( ArrayList -- )
DUP .< size()/0 >.
0 ( list n 0 )
BEGIN
2DUP < ( list n i )
WHILE
2DUP ( list n i n i )
1+ ( list n i n i+1 )
BEGIN
2DUP < ( list n i n i+1 )
WHILE
3 PICK ( list n i n j i )
2DUP ( list n i n j i j i)
8 PICK
-ROT ( list n i n j i list j i )
COMPARE-AND-SWAP
DROP ( list n i n j )
1+
REPEAT
2DROP
1+
REPEAT
2DROP
;
####################################################################################################
:ANON # Create the list [10, 20, 30, 40, 50].
@< ArrayList()/0 >@
DUP 10 SWAP .< add(Object)/1 >. DROP
DUP 30 SWAP .< add(Object)/1 >. DROP
DUP 40 SWAP .< add(Object)/1 >. DROP
DUP 20 SWAP .< add(Object)/1 >. DROP
DUP 50 SWAP .< add(Object)/1 >. DROP
; EXECUTE
BUBBLE-SORT PRINTLN
BYE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment