<style>
html, body, .ui-content {
background: #222222;
color: #00BFFF;
}
::-webkit-scrollbar {
width: 10px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: linear-gradient(180deg, #2BE8CF60 0%, #2B83E860 100%);
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: linear-gradient(180deg, #2BE8CF95 0%, #2B83E895 100%);
}
/* 設定 code 模板 */
.markdown-body code,
.markdown-body tt {
background-color: #ffffff36;
}
.markdown-body .highlight pre,
.markdown-body pre {
color: #ddd;
background-color: #00000036;
}
.hljs-tag {
color: #ddd;
}
.token.operator {
background-color: transparent;
}
</style>
###### tags: `Computer_organization`
# HW3
## Question
In the simulator, write a MIPS assembly program that sorts a sequence of positive integers entered from the console (one number in one line). The end of the sequence is indicated by a 0 (zero). Verify that the program is correct by simulation. You can use any sorting algorithm in your code except bubble sort, such as selection sort, merge sort, quick sort, etc. However, there must be a procedure call as well as looping in your code. Print out the output in ascending order on the console also, with a space between neighboring numbers. Describe your sorting algorithm in the beginning of the text file as comments. The file should be named as studentid-hw3.s.
### MIPS code
```MIPS=
#
# 此程式使用insertion sort,由左往右讀,不斷的把新的數字放到左邊已經排好的數列中
# 遇到新的數字時,不斷往左邊交換直到放到對的位置
#
# $s1放array起始位置, $s0放array的最後一個數字的下一個位置
# 使用上述兩個變數方便走訪陣列
# $s2放space的位置
#
.data
space: .asciiz " "
array: .word 0
.text
la $s0, array
la $s2, space
loop: li $v0, 5
syscall
beq $v0, $zero, out #if(input == 0) goto out
sw $v0, 0($s0) #store input to s0
addi $s0, $s0, 4 #s0加四(所以最後s0會在陣列最後一個數字的下一個)
j loop
out: la $s1, array
move $t1, $s1
sorting: addi $t1, $t1, 4 #t1儲存目前走訪到陣列的哪裡
beq $t1, $s0, sortEnd #s0 point to the arrary end (all data is sorted)
move $t2, $t1
swapnum: beq $s1, $t2, sorting #s1指到陣列起始,代表新讀到的數字已經換到最左邊,無法再往左邊,回到sorting
addi $t2, $t2, -4
lw $t4, 0($t2) #get array[i - 1]
lw $t3, 4($t2) #get array[i]
ble $t4, $t3, sorting #if(array[i - 1] <= array[i]) 放到對的位置,不須再往前交換,回到sorting
lw $t5, 0($t2) #swap
lw $t6, 4($t2) #swap
sw $t5, 4($t2) #swap
sw $t6, 0($t2) #swap
j swapnum
sortEnd: li $v0, 1 #print
lw $a0, 0($s1) #print
syscall #print
li $v0, 4 #print space
move $a0, $s2 #print space
syscall #print space
add $s1, $s1, 4
bne $s1, $s0, sortEnd #用s1走訪陣列,走到s0為止
exit: li $v0, 10 #End of Program
syscall
```
## DATE
2023/04/23