CraigWardman.com

[ x86 Assembly Bubble Sort ]

/Blog/Post

A catalogue of my discoveries in software development and related subjects, that I think might be of use or interest to everyone else, or to me when I forget what I did!

x86 Assembly Bubble Sort

Sunday, 9 January 2005


The following example shows how you can use a bubble sort in Assembly language to sort some numbers:


.386
.model flat,stdcall

option casemap:none

.data
example_data db 1,3,4,5,2,5,7,4,6,0
num_of_elements db 10

.code
start:
mov eax, dword ptr[num_of_elements] ;whatever the programmer entered
dec eax ;less one (since 10 elements = 0-9)
mov dword ptr[num_of_elements], eax ;save the new value

lea eax, example_data ;point eax to start addr
xor ebx, ebx ;reset (data reg 1)
xor edx, edx ;reset (data reg 2)
xor ecx, ecx ;reset counter

stillsort:
mov bl, byte ptr[eax] ;get 1 byte
mov dl, byte ptr[eax+1] ;and the byte to its right
cmp bl, dl ;compare the 2
jg notdone ;if byte 2 > byte 1, not sorted, go sort
push eax ;save where we are
push ecx ;save counter
lea eax, example_data ;go back to start (for test)
xor ecx, ecx ;reset counter
jmp test_sorted ;go test the whole list

notdone:
mov byte ptr[eax], dl ;put byte 2 in byte 1 position
mov byte ptr[eax+1], bl ;put byte 1 in byte 2 position
inc eax ;go to next byte
inc ecx ;count
cmp ecx, dword ptr[num_of_elements] ;10 elements (0-9)
jnz stillsort ;still sorting (no reset)
lea eax, example_data ;did all 10 elements, go again from start
xor ecx, ecx ;reset counter
jmp stillsort ;back to sort code

test_sorted:
mov bl, byte ptr[eax] ;get 1 byte
mov dl, byte ptr[eax+1] ;and the byte to its right
cmp bl, dl ;compare
jg nope ;if byte 2 > byte 1 the whole list isnt sorted
inc eax ;try next byte
inc ecx ;count
cmp ecx, dword ptr[num_of_elements] ;10 elements (0-9)
jz done ;all 10 elements are sorted
jmp test_sorted ;or loop

nope:
pop ecx ;get the back the old count
pop eax ;back to the last byte we were on
inc eax ;but 1 more now
inc ecx ;increase counter
cmp ecx, dword ptr[num_of_elements] ;10 elements (0-9)
jnz stillsort ;sorting
lea eax, example_data ;it was the last element, back to start
xor ecx, ecx ;reset counter
jmp stillsort ;sorting


done:
pop ecx ;clear stack
pop eax ;clear stack
xor eax, eax ;exit code 0
ret
end start

Labels:

Share This!



2 Comments:

Blogger Ammar said...

your program does not link correctly,
gives an error about _start

5 Dec 2008 02:31:00  
Blogger craigw said...

The syntax of the markup around the actual assembly code is valid for the MASM32 assembler/linker. I'm not sure if that would be valid in other setups. You may need to change those bits to suite your environment.

5 Dec 2008 15:33:00  

Post a Comment

<< Home

CraigWardman.com