Q2 Computer - Sort Example

An implementation of bubble sort. This makes some assumptions about values in the zero page, like the common functions.

; Sort x0 words starting at x1
; Destroys x0, x1, x2, x3, x4, x5, x6, x7
sort:
  sta   =x7         ; Return address in =x7
  lea   =0          ; Outer loop: x2 = 0 .. x0
sort_outer:
  sta   =x2
  nor   =zero
  add   =x0
  jfc   @=x7        ; x2 >= x0 - return
  lea   =1
  add   =x2         ; Inner loop: x3 = x2 + 1 .. x0
sort_inner:
  sta   =x3
  nor   =zero
  add   =x0         ; x0 - x3
  jfc   sort_next   ; done with inner loop if x3 >= x0
  lda   =x1
  add   =x2
  sta   =x4         ; @=x4 = x1[x2]
  lda   =x1
  add   =x3
  sta   =x5         ; @=x5 = x1[x3]
  lda   @=x5
  nor   =zero
  add   @=x4        ; @=x4 - @=x5
  jfc   sort_noswap ; swap if @=x4 < @=x5
  lda   @=x5
  sta   =x6
  lda   @=x4
  sta   @=x5
  lda   =x6
  sta   @=x4
sort_noswap:
  lea   =1
  add   =x3
  jmp   sort_inner
sort_next:
  lea   =1
  add   =x2
  jmp   sort_outer