Assembly bubble sort swap

2019-01-29 08:51发布

问题:

I'm trying to do a bubble sort in x86 assembly (yes it has to be bubble, as I'm not concerned about speed optimization regarding different types of sorts) and for some reason, my code will not swap the necessary values. Here is my code

mov eax, list                   ;store list in eax
mov edx,[eax+4*edi-4]           ;temp = var1
cmp edx,[eax+edi*4]             ;compare
JLE SECOND_LOOP                 ;jump if var1 < var2
mov [eax+4*edi-4],[eax+edi*4]   ;var1 = var2
mov [eax+edi*4], edx            ;var2 = temp
jmp SECOND_LOOP

At the last mov instruction where it's supposed to load the temp back into the address, it..doesn't. The EAX register has the starting address of the array which contains my list of values

0x*starting address* 0a 00 00 00 ec ff ff ff 05 00 00 00 0c 00 00 00 1e 00 00 00 fb ff ff ff ea
0x*address after   * ff ff ff 37 00 00 00 34 00 00 00 00 00 00 00

and the next address contains a few more numbers. In decimal, the numbers are 10 -20 5 12 30 -5 -22 55 52 0. Essentially right now I'm trying to move FFFFFFEC to 0000000A and then move 0000000A to FFFFFFEC. I can store it into my temp register EDX, but cannot store the value of EDX into the specific address. Any help?

回答1:

I think I'd use pointers into the current position into the list, instead of an index that needs to be scaled every time you use it:

    mov esi, offset list
top:
    mov edi, esi
inner:
    mov eax, [edi]
    mov edx, [edi+4]
    cmp eax, edx
    jle no_swap
    mov [edi+4], eax
    mov [edi], edx
no_swap:
    add edi, 4
    cmp edi, list_end - 4
    jb inner
    add esi, 4
    cmp esi, list_end - 4
    jb top


回答2:

This part of your code:

mov edx,[eax+edi*4]
mov [eax+edi*4], edx

effectively does not change anything in the memory, it reads a value from the memory and writes it back where it's just got it from.

Btw, you may be interested in the xchg instruction.