I need to sort five numbers from least to greatest.
I have been struggling with this assignment for a Little Man computer simulator. I tried adding more loops for the addition of 2 input numbers, but it never worked.
Working sorter for 3 numbers:
INP // Read in the first value
STA 91 // store it
INP // Read in the second value
STA 92 // store it
INP // Read in the third value
STA 93 // store it
LDA 92 // LOOP 1, STEP 1:
SUB 91 //
BRP STEP2 // if r91 and r92 are in order, don't swap them
LDA 92 // Begin swapping registers
STA 99 // temp = r92
LDA 91
STA 92 // r92 = r91
LDA 99
STA 91 // r91 = temp
STEP2 LDA 93 // LOOP 1, STEP 2
SUB 92
BRP STEP3 // If r92 and r93 are in order, don't swap them
LDA 93 // Begin swapping registers
STA 99 // temp = r93
LDA 92
STA 93 // r93 = r92
LDA 99
STA 92 // r92 = temp
STEP3 LDA 92 // LOOP 2, STEP 1
SUB 91
BRP STEP4 // if r91 and r92 are in order, don't swap them
LDA 92 // Begin swapping registers
STA 99 // temp = r92
LDA 91
STA 92 // r92 = r91
LDA 99
STO 91 // r91 = temp
STEP4 LDA 91 // Write out the sorted values
OUT
LDA 92
OUT
LDA 93
OUT
HLT // stop
The existing code has three steps for comparison & potential swap. The first step compares the first 2 values, the second step compares the second 2 values, and the third is like the first: it compares again the first two values.
When you have an input of 5 values, you need a loop, as otherwise you cannot fit all the necessary comparisons in the available 100 mailboxes. For that you can use an algorithm like bubble sort, which also compares adjacent pairs of values:
The code for each step is like you already have it, except that you will also make note of whether a swap was performed. This will be an indication that all the above steps need to be repeated again.
The code you have included does not use labels, and it is really a pity that the comments need to give the name to the number, while most LMC simulators support labels.
Here is how it could work: