资源描述
实验要求
实现字符串冒泡排序。
实验过程
首先在内存中定义字符串,使用的方法是
AREA SORTDATA,DATA,READWRITE
str DCB "9847210356"
len DCD 10
DCB表示在内存中开辟一个byte的空间。
DCD则表示开辟一个word的空间
采用两层循环来进行冒泡排序。
第一层循环首先把r1初始化为字符串首地址,把r5初始化为0,r5代表内循环执行次数。然后把r4 减1,因为最后的一个字符已经排好序了。如果r4 = 0, 代表排序已经完成,调到结束代码。
loop0
MOV r1,r0 ;r1 is the start address of string
SUBS r4,r4,#1 ;r4 is the last index, the counter
CMP r4,#0
BEQ end
MOV r5,#0
第二层循环就是从左往右对字符进行交换,每次把r1和r5的值都增加1。当r5=r4的时候就跳出循环,到达外层循环。
;in every loop, swap the value of contiguous two bytes from the start to start+r4
;using r1 as the address,increment in every inner loop
;using r2,r3 to load the two bytes then compare; if r3 is smaller than r2,
;then store the val in swapped place
loop
LDRB r2,[r1]
LDRB r3,[r1,#1]
CMP r2,r3
STRGTB r2,[r1,#1]
STRGTB r3,[r1]
ADD r1,r1,#1
ADD r5,r5,#1
CMP r5,r4
BNE loop
;if reaches the end, branch to outer loop
B loop0
为了让字符从小到大排列,在CMP r2,r3后,连续使用STRGT(Store Greater Than),如果r2>r3, 就分别把他们存进对方的地址实现交换。
程序执行到底,可以看到字符均已经排好序。
实验结论
通过本次实验,我对ARM汇编的基本指令更加了解了,知道了简单的分支指令,条件指令和访存指令的使用方法。
展开阅读全文