开发环境
win10+vs2017
要求
使用汇编和子程序调用实现快速排序实现快速排序
C语言代码
void quick(int *arr, int low, int high)
{
if (low >= high)return;
int tmp = arr[low];
int i = low;
int j = high;
while (i < j)
{
while (arr[j] > tmp && i<j)
j--;
arr[i] = arr[j];
while (arr[i] <= tmp && i < j)
i++;
arr[j] = arr[i];
}
arr[i] = tmp;
quick(arr, low, i - 1);
quick(arr, i + 1, high);
}
汇编代码实现
include vcIO.inc
.data
array dword 12,14,168,122,-33,56,78,99,345,66,-5;3,4,5,1,2;
format byte '%d',9,0
tmp dword 0
.code
main proc
pushad
mov eax,lengthof array - 1;//high
push eax;//把high 入栈
mov ebx,0;//保存数组元素的第一个元素的下标
push ebx;
mov ecx,offset array;保存数组元素的首地址
call quicksort
pop ebx
pop eax
print_array:
xor esi,esi;
again:
pushad
invoke printf,offset format,dword ptr [ecx+esi*4]
popad
inc esi
cmp esi,eax
jle again
popad
ret
main endp
;;快速排序子程序
quicksort proc
push ebp
mov ebp,esp
mov eax,dword ptr [ebp+12];保存high的值
mov ebx,dword ptr [ebp+8];保存low的值
;;如果if(low >= high)函数直接返回
cmp ebx,eax;
jge end_quick;结束本次函数调用
;;low和high入栈保存值
push eax
push ebx
;;给tmp赋值为array[low]
mov esi,ebx
mov esi,dword ptr [ecx + 4*esi];;
mov tmp,esi;
first_while:
mov edx,tmp
cmp [ecx+eax*4],edx
jle first_operator;;i<j如果不成立之间跳出while(tmp < arr[j]&&i<j)
cmp ebx,eax;
jge first_operator;
dec eax
jmp first_while
first_operator:
mov edx,[ecx+eax*4]
mov [ecx+ebx*4],edx;
second_while:
mov edx,tmp
cmp [ecx+ebx*4],edx
jg second_operator;
cmp ebx,eax
jge second_operator;
inc ebx
jmp second_while
second_operator:
mov edx,[ecx+ebx*4]
mov [ecx+eax*4],edx;
out_while:
cmp ebx,eax
jl first_while;如何i大于等于j结束最外层while循环
end_assign:
mov esi,eax;这个位置就是tmp要插入的位置
mov edx,tmp
mov [ecx + esi*4],edx;
end_function:
;;合适位置的前半部分_快速排序
pop ebx;默认的low也为前半部分的new_low
push eax;;保存合适的那个位置为了----》合适位置的后半部分_快速排序 (后半部分的low)
dec eax;;前半部分的new_high
push eax
push ebx
call quicksort;
pop eax
pop ebx
pop ebx
;;合适位置的后半部分_快速排序
pop eax
add ebx,1
push eax
push ebx
call quicksort;
pop eax
pop ebx
end_quick:
pop ebp
ret
quicksort endp
end main