我正在开发一个用随机值填充数组的程序,然后将它们按降序排序,然后计算中位数。我有程序工作正常,除了它收到超过100的值,然后程序吐出垃圾。我很确定错误是在我的排序过程或我的显示列表过程中。这是我认为问题所在的代码。 关于pastebin的完整代码:http://pastebin.com/5MdWijRa
;sort list
Sort PROC
push ebp
mov ebp, esp
mov edi, [ebp + 12]
mov ecx, [ebp + 8]
dec ecx ;outer loop is set to one less than request
mov ebx, 0 ;k=0
L1:
mov eax, ebx ; i = k
mov edx, eax
inc edx ; j = k+1
push ecx ;store the value of the outer loop
mov ecx, [ebp + 8] ; inner loop is set to request
L2:
cmp ecx,0
je exchangeNext
mov esi, [edi + edx*4] ; store element j of the array
cmp esi, [edi + eax*4] ;compare to element i
jg greater
inc edx
loop L2
greater:
cmp ecx,0
je exchangeNext
mov eax, edx ; i = j
inc edx ;increase j for the next iteration of the for loop
loop L2
exchangeNext:
lea esi, [edi+ebx*4] ;saved to work like a temp variable
push esi ;saved to work like a temp variable
lea esi, [edi+eax*4] ; swapping array[k] and array [i]
push esi
call exchange
pop ecx ;restore outer loop value
inc ebx ;move forward through the outer loop
loop L1
pop ebp
RET 8
Sort ENDP
exchange PROC
pushad
mov edx, [edi+eax*4] ; store the value of array[i]
mov esi, [edi+ebx*4] ; store the value of array[k]
mov [edi+eax*4], esi ; switch the values
mov [edi+ebx*4], edx
popad
RET 8
exchange ENDP
;display list
DisplayList PROC
;Set up the stack
push ebp
mov ebp,esp
mov edx, [ebp + 16] ;address of the title string
mov esi, [ebp + 12] ;address of the array
mov ecx, [ebp + 8] ; set request as the loop control
mov ebx, 0 ;keep count of how many numbers are printed
;Display the title
call WriteString
call CrLf
;Display the numbers
Show:
mov eax, [esi]
call WriteDec
mov edx, OFFSET space
call WriteString
add esi, 4 ;Move to the next element in the array
inc ebx ;Counter
cmp ebx, 10
je printLine
loop Show
cmp ecx, 0
jmp endShow
printLine:
call CrLf ;Print to the next line
mov ebx, 0 ;reset ebx
loop show
endShow:
call CrLf
pop ebp
RET 12
DisplayList ENDP
答案 0 :(得分:0)
这条线造成了混乱:
mov ecx, [ebp + 8] ; inner loop is set to request
当内循环的开始增加(inc ebx
和后代)时,重复的数量保持在[ebp+8]
,这会将循环的末尾移出数组的边界({ {1}})。计数器的起始值([ebp + 12]
)也应该减少。
在上一行之前插入该行:
ECX
有些人可能认为这是一个快速而肮脏的解决方案。我"滥用"函数作为局部变量的参数。