Small bubble sortAssembler/80386

Small bubble sort

Andrew Howe, from Core Designs (makers of Tomb Raider), sent me (Paul Hsieh) an extremely short sort loop. Originally written for WATCOM C/C++, I have stripped off the cruft so that you can see it here in its most optimal form.

;
; bubble sort
;
; input:
;   edi = pointer to array
;   ecx = number of indexes
;
; output:
;   edi = pointer to sorted array
;
; destroys:
;   eax, edx
;   eflags
;

outerloop:
        lea     ebx,[edi+ecx*4]
        mov     eax,[edi]
cmploop:
        sub     ebx,4
        cmp     eax,[ebx]
        jle     notyet
        xchg    eax,[ebx]
notyet:
        cmp     ebx,edi
        jnz     cmploop
        stods
        loop    outerloop
Notice the use of xchg, stosd, and loop, something you just wont see from C compilers. I did not bother working out the timings of this routine, simply because its a bubble sort. If you are concerned about asymptotic performance, you should be using another algorithm such as mergesort or radix sort.
Gem writer: (code) Andrew Howe
(text) Paul Hsieh
last updated: 1998-06-07