在8086中排序32位数

时间:2013-11-29 20:26:07

标签: sorting assembly x86-16

我写了这段代码并考虑了大约5个小时; 但是我坚持排序部分: 它开始循环,永不停止! 我哪里错了???

IT看到阵列没有正确获取数字。 请帮忙吗?

    page 110,100
Title 'decimal sorting'

Data_here segment
A DD Dup 20(?)
msg1 DB 'Enter a maximum 6 digits number : ',0DH,0AH,'$'
msg2 DB 0DH,0AH,'The sorted results are : ',0DH,0AH,'$'
 Data_here Ends

 Stack_here segment
   DW 10 DUP(?)
 Stack_here Ends

 Code_here segment
Assume CS:code_here , DS:Data_here ,SS:Stack_here
  Main Proc near
mov AX,Data_here
mov DS,AX
mov AX,Stack_here
mov SS,AX
Call decimal_input
call sorting
call decimal_output
mov AH,4CH
int 21H
main Endp

 decimal_input proc near
PUSH A
mov AH,09H
Lea DX,msg1
int 21H
mov CH,20

 next_number:
mov BH,6
mov DX,0
mov si,4

 next_digit:
mov AH,07H
int 21H
CMP AL,0DH
JNE check_digit
CMP BH,6
JE next_digit
DEC CH
JZ end
mov DX,0DH
mov AH,02H
int 21H
mov DX,0AH
Int 21H
jmp next_number  

check_digit:
cmp AL,30H
JB next_digit
cmp AL,39H
JA next_digit
mov AH,02H
mov DL,AL
int 21H
SUB AL,30H
SHL DX,4
ADD DL,AL
DEC SI
JZ save
DEC BH
JNZ next_digit
jmp remain

save:
mov A[DI],DX
SHL A[DI],8
add si,4
DEC BH
jmp next_digit

remain:
ADD byte ptr A[DI],DL
mov DX,0DH
mov AH,02H
int 21H
mov DX,0AH
INT 21H
INC DI
DEC CH
JNZ next_number

end:
pop A
RET
 decimal_input ENDp

 sorting proc near 
 Push A
mov SI,DI                 
check:                     
mov AX,word ptr A[SI]
mov BX,word ptr A[DI+2]
CMP AX,BX
JA change
JE extra_check
add SI,2

continue:
add DI,2
CMP DI,38
JA finish
JB check

extra_check:
mov CX,word ptr A[DI+1]
mov DX,word ptr A[DI+3] 
cmp CX,DX
JNA continue
mov word ptr A[DI+1],DX
mov word ptr A[DI+3],CX
jmp continue

change:
xchg AX,BX
mov CX,word ptr A[DI+1]
mov DX,word ptr A[DI+3]
xchg CX,DX
mov word ptr A[DI],AX
mov word ptr A[DI+1],CX
mov word ptr A[DI+2],BX
mov word ptr A[DI+3],DX
jmp continue

finish:
Add sp,2
cmp Sp,40
JE ending
mov DI,SP
jmp check
ending:
POP A
RET
sorting ENDP

 decimal_output proc near
 PUSH A
 mov AH,09H
 lea DX,msg2
 INT 21H

next_no:
 mov DL,0
 mov AL,0
 mov AH,0
next:
 CMP AL,0
 JE next1
 mov DL,byte ptr A[DI]
 ADD DL,30H
 mov AL,1
 int 21H

 next1:
 inc DI
 inc AH
 cmp AH,8
 JB next
 CMP DI,80
 JA THE_END
 mov DX,0DH
 mov AH,02H
 int 21H
 mov DX,0AH
 int 21H
 jmp next_no

 THE_END:
 pop A
 RET
 decimal_output ENDp

  code_here Ends
  END MAIN

1 个答案:

答案 0 :(得分:1)

我认为您的问题可能就在这里

Add sp,2
cmp Sp,40

您正在使用sp作为循环计数器,但您从未初始化它。另外,我也不明白为什么你首先使用sp。当然这在理论上是可行的,但是你必须在返回之前恢复它。当proc返回时,它会搞砸,因为堆栈指针已损坏。因此,您应该使用其他一些寄存器或内存变量(代码中未使用bp)。

我强烈建议您重新格式化代码,使其更具可读性(当我查看它时,我将其格式化,使其更易读):

sorting proc near 
    Push A
    mov SI,DI

check:                     
    mov AX,word ptr A[SI]
    mov BX,word ptr A[DI+2]
    CMP AX,BX
    JA change
    JE extra_check
    add SI,2

continue:
    add DI,2
    CMP DI,38
    JA finish
    JB check
 ...