I'm having problems with this selection sort, the problem is when vecnums[j] is minor to (<) vecnums[min] that I have to put j in min and then increment j by 1, after that when I load j in SI, j is no longer the value it must be (using debugger I figured out that goes to 0102, when it should be 0002). I don't know why happens that, if someone could help me I would really appreciate it :)
I apologize if I didn't express myself well, don't doubt in asking me whatever you don't understand.
Thanks for your time!
Vecnums is an array of numbers (2 bytes size) and I loaded it with: 5,-11,3,-4,10,1005,0,5,-1,23,-34,85,-30,-82,1
i resb 1
j resb 1
min resb 1
db 0
vecnums times 60 db 0
nlog resb 1 ;for the example is 15
ssort:
mov byte[i],0
mov ch,0
mov cl,[nlog]
sub cl,1
cicloi:
mov ah,0
mov al,[i]
mov [min],al ; min=i
push cx
mov cl,[i]
add cl,1
mov byte[j],cl
mov cl,[nlog]
sub cl,[j]
cicloj:
mov si,[j]
imul si,2
mov ax,word[vecnums+si]
mov si,[min]
imul si,2
mov dx,word[vecnums+si]
cmp ax,dx ;ax=vecnums[j] dx=vecnums[min]
jnl noMenor
mov ah,0 ;vecnums[j] < vecnums[min]
mov al,[j]
mov [min],al ; min=j
noMenor: ; vecnums[j] > vecnums[min]
inc byte[j]
loop cicloj
mov si,[j]
imul si,2
mov ax,word[vecnums+si]
mov si,[min]
imul si,2
mov dx,word[vecnums+si]
mov si,[j]
imul si,2
mov word[vecnums+si],dx
mov si,[min]
imul si,2
mov word[vecnums+si],ax
inc byte[i]
pop cx
loop salto
jmp finrut
salto: jmp cicloi ;the reason for this is that the jump is too long to do it with loop (couldn't assemble if I do it directly with loop)
finrut:
ret
Your j
variable is byte sized (same goes for i
and min
). However when you say mov si, [j]
you are loading 2 bytes, hence the high byte will come from the following variable (min
in case of j
). You should fix your loads, for example by using movzx si, byte [j]
Side note: it is general practice to use shifts for multiplying by powers of two.