• Sorting the bubbles

    KnivD03/28/2016 at 19:56 0 comments

    Although natively working with 16-bit words (14-bit pairs of instructions or data), CPU7 is also supposed to handle "raw" unformatted data in 8-bit, 16-bit, or 32-bit format. As an example that could be a hardware register, video memory, or anything which is not part of CPU7.

    As a small coding exercise to test the flavour of the CPU7 assembler, here is the well known "bubble sort" of an area of unformatted bytes.

    '! usage: addr len bubblesort8
    :bubblesort8
      dup 1 > if          `! check if the array is more than one element
        enter
        1 over +          `! calculate end=addr+len; stack: beg, end
        1 swap dup        `! stack: end, beg, addr
        repeat
          dup rd8         `! stack: end, beg, addr, [addr]
          1 over ++ rd8   `! stack: end, beg, addr, [addr], [addr+1]
          < if            `! stack: end, beg, addr
            ++            `! addr=addr+1
          else
            dup rd8       `! stack: end, beg, addr, [addr]
            1 over ++ rd8 `! stack: end, beg, addr, [addr], [addr+1]
            2 over wr8    `! stack: end, beg, addr, [addr]
            1 over ++ wr8 `! stack: end, beg, addr
            drop dup      `! addr=beg; stack: end, beg, addr
          endif
        dup 3 over < until
        leave             `! clean up the data stack
      endif
      drop drop           `! remove the input parameters from the data stack
    ;