vextoly/cryn

[# bubble sort over a heap block of int64, using element helpers #]
make string "\n" nl

define newline result nothing
  address nl
  output text
  set nothing
  return
end

define getelem address array of int64 blk int64 idx result int64
  move idx
  read
  push
  move blk
  read
  move at
  pop
  move index
  read
  return
end

define setelem address array of int64 blk int64 idx int64 val result nothing
  move val
  read
  push
  move idx
  read
  push
  move blk
  read
  move at
  pop
  move index
  pop
  write
  set nothing
  return
end

define load address array of int64 blk int64 idx int64 val result nothing
  move blk
  read
  push
  move idx
  read
  push
  move val
  read
  push
  call setelem
  set nothing
  return
end

define put int64 v result nothing
  move v
  read
  output
  call newline
  set nothing
  return
end

define main
  make 8 of int64 a
  make int64 i
  make int64 j
  make int64 tmp

  move a
  read
  push
  set 0
  push
  set 42
  push
  call load

  move a
  read
  push
  set 1
  push
  set 17
  push
  call load

  move a
  read
  push
  set 2
  push
  set 99
  push
  call load

  move a
  read
  push
  set 3
  push
  set 3
  push
  call load

  move a
  read
  push
  set 4
  push
  set 58
  push
  call load

  move a
  read
  push
  set 5
  push
  set 21
  push
  call load

  move a
  read
  push
  set 6
  push
  set 7
  push
  call load

  move a
  read
  push
  set 7
  push
  set 65
  push
  call load

  set 7
  move i
  write
  set 0
  home

  mark outer
  move i
  read
  compare 0
  jump sorted when less
  set 0
  home

  set 0
  move j
  write
  set 0
  home

  mark inner
  move i
  read
  push
  move j
  read
  compare
  jump nextPass when greater-or-equal
  set 0
  home

  move a
  read
  push
  move j
  read
  push
  call getelem
  move tmp
  write

  move a
  read
  push
  move j
  read
  add 1
  push
  call getelem
  push
  move tmp
  read
  compare
  jump noSwap when less-or-equal

  move a
  read
  push
  move j
  read
  push
  move a
  read
  push
  move j
  read
  add 1
  push
  call getelem
  push
  call setelem

  move a
  read
  push
  move j
  read
  add 1
  push
  move tmp
  read
  push
  call setelem

  mark noSwap
  move j
  read
  add 1
  move j
  write
  set 0
  home
  jump inner

  mark nextPass
  move i
  read
  subtract 1
  move i
  write
  set 0
  home
  jump outer

  mark sorted
  set 0
  move i
  write
  set 0
  home

  mark print
  move i
  read
  compare 8
  jump done when greater-or-equal
  set 0
  home

  move a
  read
  push
  move i
  read
  push
  call getelem
  push
  call put

  move i
  read
  add 1
  move i
  write
  set 0
  home
  jump print

  mark done
  move a
  read
  free
  return
end