I have a dword array of 15 random integers that is stored in esi. I have a bubble sort algorithm below which is supposed to arrange the values from lowest to highest. However when my program runs through this algorithm it doe not seem to touch any of the values and when I print the array it is exactly as it was before. Thoughts?
BubbleSort PROC USES eax ebx ecx edx esi
mov ecx, 0
mov ecx, 15
OUTER_LOOP:
push ecx
mov ecx,0
mov ecx,14
mov esi, OFFSET arr
COMPARE:
mov ebx,0
mov edx,0
mov bl, [esi]
mov dl, [esi+1]
cmp bl,dl
jg SWAP
CONTINUE:
add esi,4
loop COMPARE
mov esi, OFFSET arr
pop ecx
loop OUTER_LOOP
jmp FINISHED
SWAP:
mov bl, [esi]
mov dl, [esi+1]
xchg bl,dl
mov [esi],dl
mov [esi+1],bl
jmp CONTINUE
FINISHED:
ret
BubbleSort ENDP
Thanks for your help in advance.
EDIT:
I found different problems in your code. I’ve fixed them below and ESI is actually changed (not sorted because I think the sorting algorithm is wrong but didn’t have time yet to change it)
1- mov reg,0
It’s better to xor the register instead of moving 0 to it. XOR instruction is shorter.
2- In the CONTINUE loop I use add esi,2 (maybe you’re on 64bit windows?)
3- In the SWAP loop, the first 2 mov instructions are useless. I removed them.
4- In the SWAP loop, you need to swap the lines where you put the values back in esi and esi+1 (actually you don’t even need the xchg instruction.)
Now ESI is changed. You need to work on the sorting algorithm.
EDIT:
In the outer loop you have 2 mov esi, OFFSET arr
and the second one happens just before exiting. So you’re basically putting the array offset back in ESI like it was at the start.
The USES ESI note below holds. You need to remove it.
Also what is ECX used for in this procedure? It’s never used but you’re assigning values, pushig and poping them?
USES eax ebx ecx edx esi
This masm helper pushes ESI on the stack.
When you exit the procedure it pops it out as it was before.
So you probably don’t want to include ESI up there.
Note, you also want to put your DWORD in another register like EAX. There are some case when entering a procedure ESI and the likes are pushed anyway.