Quicksort in Assembly

Quick sort inside a C++ asm block use in either an ASM app or C++ one.

Quicksort is a great, reliable general purpose sorting algorithm.

Call _qsort_int_asm directly if you know the array is two or larger

// assembly versions; uses both but call qsort_int_asm in your app
void __stdcall _qsort_int_asm(int *array, unsigned int siz);
void __stdcall qsort_int_asm(int *array, unsigned int siz)
{
#define PIVOT ebx
#define LEFT	esi
#define RIGHT edi
#define TEMP	eax
#define TEMP2 ecx
#define SIZE	edx
	__asm
	{
		mov SIZE,dword ptr [siz]
		cmp SIZE,2
		jl the_end
		push SIZE
		mov TEMP,dword ptr [array]
		push TEMP
		call _qsort_int_asm
the_end:
	}
}
void __stdcall _qsort_int_asm(int *array, unsigned int siz)
{
	__asm
	{
		mov LEFT,dword ptr [array]
		mov SIZE,dword ptr [siz]

		mov eax,SIZE
		shr eax,1
		mov PIVOT,LEFT
		mov PIVOT,dword ptr [PIVOT+eax*4]
		
		mov eax,SIZE 
		mov RIGHT,LEFT
		lea RIGHT,[RIGHT+eax*4-4] 

main_loop: ;while(true){
left_loop:
		cmp LEFT,RIGHT
		jg right_loop
		cmp [LEFT],PIVOT
		jge right_loop
		add LEFT,4
		jmp left_loop
right_loop:
		cmp LEFT,RIGHT
		jg loop_break
		cmp [RIGHT],PIVOT
		jle loop_break
		sub RIGHT,4
		jmp right_loop
loop_break:
		cmp LEFT,RIGHT
		jg loop_end
swap_left_right:
		mov TEMP,[LEFT]
		mov TEMP2,[RIGHT]
		mov [LEFT],TEMP2
		mov [RIGHT],TEMP
		add LEFT,4
		sub RIGHT,4
		jmp main_loop
loop_end:
		;qsort(array, right - array + 1);
		mov eax,RIGHT
		sub eax,dword ptr [array]
		sar eax,2
		add eax,1
		cmp eax,2
		jl qsort2
		push eax	
		mov ebx,dword ptr [array] 
		push ebx	

		call _qsort_int_asm

qsort2:
		;qsort(left, array + siz - left);
		mov eax,dword ptr [siz]
		mov ebx,dword ptr [array]
		lea ecx,[ebx+eax*4]
		sub ecx,LEFT
		sar ecx,2
		cmp ecx,2
		jl the_end
		push ecx 
		push LEFT

		call _qsort_int_asm

the_end:
	}
}