【汇编程序】实现冒泡排序子程序(BubbleSort)

程序需求:编程写一个名为BubbleSort的冒泡排序子程序,主子程序间的参数传递通过堆栈完成;并写主程序验证它。    

编程思路:主程序向子程序传递数组的时候,传递的是数组的首地址,也就是传递的是指针,所以子程序中寻址采用间接寻址方式。

开发环境

Win10 + VS2017

C语言代码实现如下:

#include 

int array[10] = { 10,9,8,7,6,5,4,3,2,1 };
void BubbleSort(int arr[], int n)
{
	for (int i = 0; i < n - 1; i++)
		for (int j = 0; j < n - i - 1; j++)
		{
			if (arr[j] > arr[j + 1])
			{
				int tmp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = tmp;
			}
		}
}
int main()
{
	BubbleSort(array, 10);
	for (int i = 0; i < 10; i++)
		printf("%d\t", array[i]);
	return 0;
}

汇编语言代码实现如下:

INCLUDELIB kernel32.lib
INCLUDELIB ucrt.lib
INCLUDELIB legacy_stdio_definitions.lib
 
.386
.model flat,stdcall
 
ExitProcess PROTO,
dwExitCode:DWORD
 
printf    PROTO C : dword,:vararg
scanf    PROTO C : dword,:vararg
 
.data
array dword 10,9,8,7,6,5,4,3,2,1
msg byte '%d',9,0

.code

main Proc
	mov ecx,lengthof array - 1
	mov esi,offset array
	push ecx
	push esi
	call BubbleSort

	mov ecx,lengthof array
	xor esi,esi
again:
	pushad
	invoke printf,offset msg,dword ptr array[esi*4]
	popad
	inc esi
	loop again

	push 0h
	call ExitProcess
main endp

BubbleSort proc
	push ebp
	mov ebp,esp

	pushad

	mov edx,dword ptr [ebp+8]
	mov ecx,dword ptr [ebp+12]
again:
	push ecx
	xor esi,esi

l1:
	mov eax,[edx + esi*4]
	mov ebx,[edx + esi*4 + 4]
	cmp eax,ebx
	jle next
	mov [edx + esi*4],ebx
	mov [edx + esi*4 + 4],eax
next:
	inc esi
	loop l1

	pop ecx
	loop again

	popad

	pop ebp
	ret 8
BubbleSort endp

end main

编译运行后结果如下:【汇编程序】实现冒泡排序子程序(BubbleSort)_第1张图片

 

你可能感兴趣的:(【汇编程序】)