Sikau

Assembly language · Day 12 · about 55 min

Capstone: Sort and print

A full program: main, a bubble sort that swaps in memory, and a printer.

A real program

Bring everything together: a main that calls a sort and a print routine, loops inside loops, words loaded and stored in memory, branches, and ecalls — the shape of real low-level code.

Plan the program

When something goes wrong, step through the program one instruction at a time and watch the registers and memory change. Low-level bugs are almost always a wrong offset, a forgotten save or a register reused too early.

Take your time with this one: careful register bookkeeping matters more than speed.

Split the capstone into three routines with clear contracts. sort(address, n) rearranges words in place. print_array(address, n) prints them with separators. main loads the array's address and length, calls sort, calls print_array and exits. Write and test each routine on its own before connecting them.

  • sort: two nested loops; compare neighbours, swap with lw/sw.
  • print_array: loop, ecall 1 for each number, ecall 11 for separators.
  • main: la, li, call sort, call print_array, ecall 10.
  • Leaf routines need no frame; main needs one only if it must return.

Print the array before sorting too — it's the quickest way to confirm the data and the printer work.

The rest of this lesson

  • Bubble sort in memoryexplain
  • Looking backexplain
  • main, top to bottomorder
  • Routine to techniquematch
  • Sort and printchallenge
  • Badge quizquiz
  • Assembly language: complete!recap

Continue this lesson free — run real code in your browser

Continue with Google

See all 12 lessons of Assembly language