我正在为我的计算机系统类的汇编代码中创建一个冒泡排序函数。
我的功能看起来像这样
int sorter(int* list, int count, int opcode) {
__asm {
mov ebx, opcode ; opcode in ebx
push 0 ; outer count
mov ecx, 0 ; start ecx at 0 to start loop
mov esi, list ; set esi to list value/ starting address
jmp iloop ; jump to inner loop
oloop: //OUTER LOOP
push ecx ;
mov ecx, 0 ; put the 2nd value in the list in the inner loop count
iloop: // inner loop
mov edx, dword ptr[esi + 4 * ecx]; move first value in edx
mov eax, dword ptr[esi + 4 + 4 * ecx]; move next value in list to eax
cmp ebx, 2 ; compare opcode with 2
je dsnd ; if opcode is equal to 2 then we are using descending order
cmp eax, edx ; compare values at eax and edx
jg no_swap ; if value is greater eax(2nd value) then dont swap /ascending order
cont: //continue from descend
push edx ; push contents of edx to stack
pop dword ptr[esi + 4 + 4 * ecx]; pop the contents on stack to address of value in eax
push eax ; push value in eax to stack
pop dword ptr[esi + 4 * ecx]; pop value on stack to address of value previously in eax
no_swap: //no value swap
inc ecx ; increment inner count
cmp ecx, count ; compare inner loop count to acutal length
jne iloop ; if not equal jump back to inner loop
pop ecx ; get outer count
inc ecx ; to check for n-1 in outer loop
cmp ecx, count ; compare outer loop count to length
jne oloop ; if not equal jump back to outer loop
jmp done ;
dsnd:
cmp eax, edx ; compare values at eax and edx
jl no_swap ; if value is less then dont swap
jmp cont ; continue with loop
done:
}
opcode
对于升序排序为1
,对于降序排序为2
,
list
是指向整数列表的指针,count
是列表中的整数数量
对于升序排序,我的程序运行正常,但随着降序我遇到了这些测试运行中显示的问题:
input 10 -20 5 12 30 -5 -22 55 52 0
Number of integer = 10
Ascend_or_Descend = 1
-22 -20 -5 0 5 10 12 30 52 55 # correct
input 48 -24 48 -24 10 100 -10 60 -256 10 -10 4096 -1024 60 10 -10
Number of integer = 16
Ascend_or_Descend = 1
-1024 -256 -24 -24 -10 -10 -10 10 10 10 48 48 60 60 100 4096 # correct
input 10 -20 5 12 30 -5 -22 55 52 0
Number of integer = 10
Ascend_or_Descend = 2
4283780 55 52 30 12 10 5 0 -5 -20 # incorrect
input 48 -24 48 -24 10 100 -10 60 -256 10 -10 4096 -1024 60 10 -10
Number of integer = 16
Ascend_or_Descend = 2
1500056 4096 100 60 60 48 48 10 10 10 -10 -10 -10 -24 -24 -256 # incorrect
似乎采用最低值并将其与地址交换。我不是集会的专家。