在程序集8086中找到给定数组中的最小值

时间:2017-01-03 14:58:59

标签: assembly emu8086 x86-16

我编写了一个代码来计算给定数组中的最小值,并且想法是取第一个元素(考虑它是最小值)并将其与剩余元素进行比较然后交换值以防我找到更小的值这是我的代码:

array dw 7,4,12,5,1

mov si,00h
mov ax,array[si]


mov cx,5

minimum:

inc si ;find the minimum value 
mov dx,array[si]
cmp ax,dx 
jb nochange 

swap:
xchg ax,dx

nochange:
dec cx 
cmp cx,0
JNE minimum

lastcmp:  ; to compare the last item with the minimum value and swap if it's smaller  
mov dx,array[si]
cmp ax,dx
jb endi
xchg ax,dx 


end 

但似乎我在这里有一个问题,因为它比较所有元素但不是最后一个,所以它总是给我(4),它是给我(1),任何帮助!

1 个答案:

答案 0 :(得分:1)

SomeText A123B456.Thing SomeMoreText

您处理的数组总共只有5个元素。您已经在单独的步骤中删除了第一个元素,因此您的代码只能与剩余的4个元素进行比较!

mov cx,5

由于数组包含单词,因此需要将inc si 寄存器增加2才能进入下一个数组元素。请记住,在像SI这样的指令中,mov dx,array[si]部分实际上是数组中的偏移量(以字节数表示的位移)。它不是像通常的高级语言那样的索引。

[si]

这里的dec cx cmp cx,0 JNE minimum 指令非常无用,因为cmp cx,0指令已经根据后面的条件跳转定义了零标志。将代码缩短为:

dec cx
dec cx
jnz minimum

为什么你认为你最后一节需要这个?结果已经在lastcmp: ; to compare the last item with the minimum value and swap if it's smaller mov dx,array[si] cmp ax,dx jb endi xchg ax,dx 寄存器中。此外,由于您没有更改AX寄存器,因此这个额外的比较只会复制您在循环中执行的最后一个!