Reputation: 1
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
Upvotes: 0
Views: 708
Reputation: 350335
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:
#input: 5 3 4 2 1
INP
STA NUM1
INP
STA NUM2
INP
STA NUM3
INP
STA NUM4
INP
STA NUM5
BEGIN LDA ZERO
STA DIRTY
LDA NUM2
SUB NUM1
BRP STEP2
LDA ONE
STA DIRTY
LDA NUM1
STA TEMP
LDA NUM2
STA NUM1
LDA TEMP
STA NUM2
STEP2 LDA NUM3
SUB NUM2
BRP STEP3
LDA ONE
STA DIRTY
LDA NUM2
STA TEMP
LDA NUM3
STA NUM2
LDA TEMP
STA NUM3
STEP3 LDA NUM4
SUB NUM3
BRP STEP4
LDA ONE
STA DIRTY
LDA NUM3
STA TEMP
LDA NUM4
STA NUM3
LDA TEMP
STA NUM4
STEP4 LDA NUM5
SUB NUM4
BRP CHECK
LDA ONE
STA DIRTY
LDA NUM4
STA TEMP
LDA NUM5
STA NUM4
LDA TEMP
STA NUM5
CHECK LDA DIRTY
BRZ OUTPUT
BRA BEGIN
OUTPUT LDA NUM1
OUT
LDA NUM2
OUT
LDA NUM3
OUT
LDA NUM4
OUT
LDA NUM5
OUT
HLT
NUM1 DAT
NUM2 DAT
NUM3 DAT
NUM4 DAT
NUM5 DAT
DIRTY DAT
TEMP DAT
ONE DAT 001
ZERO DAT 000
<script src="https://cdn.jsdelivr.net/gh/trincot/[email protected]/lmc.js"></script>
Upvotes: 0