x64平台AT&T汇编实现快速排序函数

代码如下,思路和c实现大同小异,主要是寄存器的使用以及地址的使用,具体参见注释。

#	void qsort(int* start, int* end)			                        #	start = &a[0], end = &a[n]
qsort:
	lea 4(%rdi), %rax							        #	tmp = &a[1]
	cmp %rsi, %rax								        #	if tmp >= end
	jge .L4										#		then return	
	pushq %rsi									#	save rsi
	pushq %rdi									#	save rdi
	movl (%rdi), %eax							        #	save first ele
.L1:											
	cmp %rsi, %rdi								        #	if start >= end
	jge .L2										#		end loop
	subq $4, %rsi								        #	--end
	movl (%rsi), %ecx							        #	tmp1 = *end	
	cmp %eax, %ecx								        #	if tmp1 >= a[0]
	jge .L1										#		loop
	movl %ecx, (%rdi)							        #	*start = tmp1

.L2:
	cmp %rsi, %rdi								        #	if start >= end
	jge .L3										#		end loop
	addq $4, %rdi								        #	++start
	movl (%rdi), %ebx							        #	tmp2 = *start
	cmp %eax, %ebx								        #	if tmp2 <= start
	jle .L2										#		loop
	movl %ebx, (%rsi)							        #	*start = *end
	
	jmp .L1										#	loop
.L3:											#	if able to jump out of loop, then start = end = then location they meeted 
	movl %eax, (%rdi)							        #	*start = tmp
	popq %rdi									#	return start

	pushq %rsi									#	save end(the meeting place)
	call qsort									#	qsort(start, the meeting place)

	popq %rdi									#	set start to the meeting place
	addq $4, %rdi								        #	++start

	popq %rsi									#	recover end
	call qsort									#	qsort(the meeting place, end)

.L4:
	ret


你可能感兴趣的:(汇编)