Reputation: 19
I wrote a code to calculate the minimum value in the given array and idea is to take the first element (considering that it's the min value) and compare it with the remaining elements then exchange the values in case that I find smaller one and here is my code :
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
but it seems like I have a problem here as it compares all elements but not the last one so it always gives me (4) and it is to give me (1) ,, any help !
Upvotes: 1
Views: 10110
Reputation: 9899
mov cx,5
The array that you proces has just 5 elements in total. You've taken away the first element in a separate step, therefore your code can only perform compares with the remaining 4 elements!
inc si
Since the array contains words, you need to increase the SI
register by 2 in order to advance to the next array element. Remember that in an instruction like mov dx,array[si]
the [si]
part is actually an offset in the array (a displacement expressed in number of bytes). It is not an index like in the usual high level languages.
dec cx cmp cx,0 JNE minimum
The cmp cx,0
instruction here is quite useless since the dec cx
instruction already defines the zero flag as needed by the conditional jump that follows. Shorten the code to:
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
Why do you think that you need this last section? The result is already in the AX
register. Moreover since you didn't change the SI
register this extra compare just duplicates the last one you did in the loop!
Upvotes: 1