2020/c64/btree.asm

106 lines
1.9 KiB
NASM

// vim: filetype=kickass
.const next_index = $02
.const input = $03
// NOTE Assumes the tree is zeroed
tree_insert:
ldx #0
!loop:
lda tree_values_lo, x
bne !not_zero+
lda tree_values_hi, x
bne !not_zero+
// Insert the node
lda input
sta tree_values_lo, x
lda input + 1
sta tree_values_hi, x
inc next_index
rts
!not_zero:
sec
lda tree_values_lo, x
sbc input
lda tree_values_hi, x
sbc input + 1
bcc !greater+
!less:
lda tree_left, x
bne !+
lda next_index
sta tree_left, x
!:
lda tree_left, x
tax
jmp !loop-
!greater:
lda tree_right, x
bne !+
lda next_index
sta tree_right, x
!:
lda tree_right, x
tax
jmp !loop-
brk
tree_contains:
ldx #0
!loop:
sec
lda tree_values_lo, x
sbc input
beq !lo_eq+
lda tree_values_hi, x
sbc input + 1
bcc !greater+
!less:
lda tree_left, x
beq !not_found+
tax
jmp !loop-
!greater:
lda tree_right, x
beq !not_found+
tax
jmp !loop-
!not_found:
// Match not found, set 1 so bne branches
lda #1
rts
!lo_eq:
lda tree_values_hi, x
sbc input + 1
bne !less-
// Match found, set 0 so beq branches
lda #0
rts
brk
.align $100
tree_values_lo:
.fill 256, 0
tree_values_hi:
.fill 256, 0
tree_left:
.fill 256, 0
tree_right:
.fill 256, 0