如何在汇编代码中制作排序算法,在LC3中

时间:2017-05-02 10:28:11

标签: algorithm sorting assembly lc3

我有一个简单的循环,它接受名称并打印名称而不保存它。

    looptext getc         ;starts text get loop for name
                          ;since name isn't re-used, we don't have to save it
    add r1, r0, -10       ;Test for enter character
    brz finishloop1       ;if enter, cancel the text loop
    OUT                   ;If it's not enter, print out the character typed
    br looptext           ;Go back to loop
finishloop1

程序然后要求以空格分隔的ID号。所有这些值都保存在一个数组和每个循环中,它检查新输入是否为“新”最低值或“新”最高值并将其设置为可敬的寄存器。

[为版权起见的删除代码]

在代码的末尾,我需要添加一个排序算法,我只剩下一个字符数组。

我需要遍历数组的每个索引,并按数字顺序重排数字(从最小到最大)。

1 个答案:

答案 0 :(得分:1)

非常感谢大家的提示和技巧。特别感谢@ Ped7g链接我那个排序算法页面。我最终搜索并实际上在gitub上找到了一个已经在汇编代码中写出泡泡算法的人。所以,谢谢你间接给我答案。

注意:对于任何未来的人来这里寻找答案,这里是泡泡排序算法代码的链接: https://github.com/oc-cs360/s2014/blob/master/lc3/bubblesort.asm。这是大学课程讲义的一部分。

; Implementing bubble sort algorithm
;   R0  File item
;   R1  File item
;   R2  Work variable
;   R3  File pointer
;   R4  Outer loop counter
;   R5  Inner loop counter


            .ORIG   x3000

; Count the number of items to be sorted and store the value in R7

            AND     R2, R2, #0  ; Initialize R2 <- 0 (counter)
            LD      R3, FILE    ; Put file pointer into R3
COUNT       LDR     R0, R3, #0  ; Put next file item into R0
            BRZ     END_COUNT   ; Loop until file item is 0
            ADD     R3, R3, #1  ; Increment file pointer
            ADD     R2, R2, #1  ; Increment counter
            BRNZP   COUNT       ; Counter loop
END_COUNT   ADD     R4, R2, #0  ; Store total items in R4 (outer loop count)
            BRZ     SORTED      ; Empty file

; Do the bubble sort

OUTERLOOP   ADD     R4, R4, #-1 ; loop n - 1 times
            BRNZ    SORTED      ; Looping complete, exit
            ADD     R5, R4, #0  ; Initialize inner loop counter to outer
            LD      R3, FILE    ; Set file pointer to beginning of file
INNERLOOP   LDR     R0, R3, #0  ; Get item at file pointer
            LDR     R1, R3, #1  ; Get next item
            NOT     R2, R1      ; Negate ...
            ADD     R2, R2, #1  ;        ... next item
            ADD     R2, R0, R2  ; swap = item - next item
            BRNZ    SWAPPED     ; Don't swap if in order (item <= next item)
            STR     R1, R3, #0  ; Perform ...
            STR     R0, R3, #1  ;         ... swap
SWAPPED     ADD     R3, R3, #1  ; Increment file pointer
            ADD     R5, R5, #-1 ; Decrement inner loop counter
            BRP     INNERLOOP   ; End of inner loop
            BRNZP   OUTERLOOP   ; End of outer loop
SORTED      HALT

FILE        .FILL   x3500       ; File location
            .END
相关问题