1. 程式人生 > >WinMIPS64實現氣泡排序

WinMIPS64實現氣泡排序

本程式碼實現的是《計算機組成與設計:硬體/軟體介面》第94頁的sort過程

相對於書本,本程式碼完善了資料準備,引數準備等細節, 把它變成了可執行的程式

.data
m1: .asciiz "before sort:"
m2: .asciiz "after sort:"
array: .word32 8,6,3,7,1,0,9,4,5,2

CONTROL: 		.word32 0x10000
DATA:       .word32 0x10008

.text
main:
lwu $t8,DATA($zero)
lwu $t9,CONTROL($zero)

daddi $sp,$zero,100
daddi $t1,$zero,m1			;輸出字串m1
sw $t1,0($t8)
daddi $t1,$zero,4
sw $t1,0($t9)

daddi $t1,$zero,array				;輸出排序前的陣列
daddi $t3,$zero,array
daddi $t3,$t3,32
lw $t4,0($t1)
sw $t4,0($t8)
daddi $t2,$zero,1
sw $t2,0($t9)
for:
daddi $t1,$t1,4
lw $t4,0($t1)
sw $t4,0($t8)
daddi $t2,$zero,1
sw $t2,0($t9)
bne $t1,$t3,for

daddi $a0,$zero,array		;為排序準備引數
daddi $a1,$zero,10

jal sort

output:
daddi $t1,$zero,m2			;輸出字串m2
sw $t1,0($t8)
daddi $t1,$zero,4
sw $t1,0($t9)

daddi $t1,$zero,array				;輸出排序後的陣列
daddi $t3,$zero,array
daddi $t3,$t3,36
lw $t4,0($t1)
sw $t4,0($t8)
daddi $t2,$zero,1
sw $t2,0($t9)
forr:
daddi $t1,$t1,4
lw $t4,0($t1)
sw $t4,0($t8)
daddi $t2,$zero,1
sw $t2,0($t9)
bne $t1,$t3,forr

halt

sort:
daddi $sp,$sp,-20			;將暫存器的值儲存在棧
sw $ra,16($sp)
sw $s3,12($sp)
sw $s2,8($sp)
sw $s1,4($sp)
sw $s0,0($sp)

daddi $s2,$a0,0			;移動引數,a0存的是陣列的地址,a1存的是需要排序的個數
daddi $s3,$a1,0

daddi $s0,$zero,0				;外部迴圈,s0代表i
for1tst:
slt $t0,$s0,$s3				;判斷s0(即i)是否小於s3(n),如果小,則進如內部迴圈
beq $t0,$zero,exit1

daddi $s1,$s0,-1			;內部迴圈開始,暫存器s1存的是j,j=i-1
for2tst:
slti $t0,$s1,0				;如果j<0,跳出迴圈
bne $t0,$zero,exit2
dsll $t1,$s1,2					;計算出t1,t2即相對地址
dadd $t2,$s2,$t1
lw $t3,0($t2)					;利用t1,t2取對應的數
lw $t4,4($t2)
slt $t0,$t4,$t3				;如果數1大於數2,則跳出內部迴圈,不然則呼叫swap函式
beq $t0,$zero,exit2

daddi $a0,$s2,0				;傳遞引數並呼叫swap函式
daddi $a1,$s1,0
jal swap

daddi $s1,$s1,-1		;內部迴圈
j for2tst

exit2:
daddi $s0,$s0,1			;外部迴圈
j for1tst

exit1:
lw $s0,0($sp)
lw $s1,4($sp)
lw $s2,18($sp)
lw $s3,12($sp)
lw $ra,16($sp)
daddi $sp,$sp,20
jr $ra

swap:
dsll $t1,$a1,2				;取第k個數的相對地址
dadd $t1,$a0,$t1		;取第k個數的絕對地址
lw $t0,0($t1)
lw $t2,4($t1)
sw $t2,0($t1)
sw $t0,4($t1)
jr $ra