0

我正在寻找一个 e-LMC 扩展的小人计算机程序,它将接受不确定的输入并对它们进行冒泡排序。我需要有更多的连续输入,然后进行冒泡排序。

INP //read 1st value
STA 0 // for store
INP // read 2nd value
   STA 1 // store
INP // read 3rd value
STA 2 // store
LDA 1 // LOOP 1, STEP 1:
    SUB 0 //
BRP STEP2 // if R0 and R1 are in order, don't swap them
LDA 1 // Begin swapping registers
STA 3   
LDA 0
STA 1 // R1 = R0
LDA 3
STA 0 //R0 = temp
STEP2 LDA 2 // LOOP 1, STEP 2
SUB 1
BRP STEP3 // If R1 and R2 are in order, don't swap them
LDA 2 // Begin swapping registers
STA 3 // temp =R2
LDA 1
STA 2 //R2=R1
   LDA 3
STA 1 // R1 = temp
STEP3 LDA 1 // LOOP 2, STEP 1
SUB 0
BRP STEP4 // if R0 andR1 are in order, don't swap them
LDA 1 // Begin swapping registers
STA 3 // temp = R1
LDA 0
STA 1 //R1=R0
LDA 3
STO 0 // R0 = temp

STEP4 LDA 0
OUT
   LDA 1
   OUT
LDA 2
OUT
   HLT
4

1 回答 1

0

由于我对 e-LMC 不熟悉,我在这里提供一个纯 LMC 实现。缺点当然是 LMC 的空间有限。由于下面的代码不包括输入数组,占用了62个邮箱,所以最多可以输入38个值(这个未验证)。

我选择用终止值 0 标记输入的结尾,即要排序的值不能包含 0。

正如您在评论中已经指出的那样,此解决方案严重依赖于自修改代码。所有标有get***,set***cmp***动态更改为指向数组中正确元素的指令。

您可以在此代码段中运行此代码(它会加载一个模拟器):

#input: 5 2 4 1 3 0
         LDA setfirst
         STA setcurr1
input    INP
setcurr1 STA array
         BRZ isempty
         LDA setcurr1
         ADD one
         STA setcurr1
         BRA input

isempty  LDA array
         BRZ zero     ; empty array
sort     LDA getfirst ; init "curr" indices
         STA getcurr1
         STA getcurr2
         LDA setfirst
         STA setcurr2
         LDA cmpfirst
         STA cmpcurr
         STA issorted ; bool: assume sorted

loop     LDA getcurr1 ; set "next" indices
         ADD one
         STA getnext1
         STA getnext2
         LDA setcurr2
         ADD one
         STA setnext

getnext1 LDA array
         BRZ check    ; end of array
cmpcurr  SUB array
         BRP inc      ; no swap needed
getcurr1 LDA array    ; swap
         STA temp
getnext2 LDA array
setcurr2 STA array
         LDA temp
setnext  STA array
         LDA zero
         STA issorted ; was not sorted yet
inc      LDA getnext1  ; increment "cur" indices
         STA getcurr1
         LDA setnext
         STA setcurr2
         LDA cmpcurr
         ADD one
         STA cmpcurr
         BRA loop

check    LDA issorted
         BRZ sort

getcurr2 LDA array
         BRZ zero     ; all done
         OUT
         LDA getcurr2
         ADD one
         STA getcurr2
         BRA getcurr2

; constants:
zero     HLT
one      DAT 1        
getfirst LDA array
setfirst STA array
cmpfirst SUB array

; variables:
issorted DAT ; boolean
temp     DAT ; for swapping
array    DAT ; start of array

<script src="https://cdn.jsdelivr.net/gh/trincot/lmc@v0.77/lmc.js"></script>

正如您所写的,e-LMC 是 LMC 的扩展,具有更多的寄存器和寻址方法,我想将其更改为可以利用这些扩展的程序并不难。

于 2020-10-27T16:04:56.440 回答