要求:
- 从键盘输入一批十进制数值数据,存入到数组array中,并重新显示出来;
- 对数组array进行冒泡排序
- 将排序结果显示出来
结果:
代码:
; multi-segment executable file template.
data segment
; add your data here!
pkey db "press any key...$"
array dw count dup(?)
N =($-array)/2
count = 10
wtemp dw ?
indata db 'Please input 10 numbers: ',0
orgdata db 'The original numbers : ',0
sortdata db 'The number after bubble sort: ',0
ends
stack segment
dw 128 dup(0)
ends
code segment
start:
; set segment registers:
mov ax, data
mov ds, ax
mov es, ax
; add your code here
lea dx, pkey
mov ah, 9
int 21h ; output string at ds:dx
; wait for any key....
call dpcrlf
mov si, offset indata
push si
call print
add sp, 2
;-------------------代码段(主程序)
mov cx, count
mov bx, offset array
again: ;读数据
call read
mov [bx], ax
inc bx
inc bx
call dpcrlf
loop again
mov si, offset orgdata
push si
call print
add sp, 2
mov cx, count
mov bx, offset array
again1: ;写数据
mov ax, [bx]
mov wtemp, ax
call write
inc bx
inc bx
mov dl, ' '
mov ah, 02
int 21h
loop again1
call dpcrlf
call bubble ;冒泡排序
mov si, offset sortdata
push si
call print
add sp, 2
mov cx, count
mov bx, offset array
again2:
mov ax, [bx] ;排序输出
mov wtemp, ax
call write
inc bx
inc bx
mov dl, ' '
mov ah, 02
int 21h
loop again2
call dpcrlf
mov ax, 4c00h ; exit to operating system.
int 21h
;---------------------子程序
;冒泡排序
bubble proc
mov cx, count
dec cx
outcir:
mov bx, 0
mov di, cx
incir:
mov ax, array[bx]
cmp ax, array[bx+2]
jle next
xchg ax, array[bx+2]
mov array[bx], ax
next:
add bx, 2
loop incir
mov cx, di
loop outcir
ret
bubble endp
;---------------------子程序
;读数据
read proc
push bx
push cx
push dx
xor bx, bx
xor cx, cx
mov ah, 1
int 21h
cmp al, '+' ;是"+",继续输入字符
jz read1 ;相等就跳到read1
cmp al, '-' ;是"-",设置-1标志
jnz read2 ;不相等就跳到read2
mov cx, -1
read1:
mov ah, 1
int 21h
read2:
cmp al, '0'
jb read3
cmp al, '9'
ja read3
sub al, 30h ;0-9之间的字符,-30h则转换为十进制
;利用移位指令,实现数值乘10:BX←BX×10
shl bx, 1
mov dx, bx
shl bx, 1
shl bx, 1
add bx, dx
mov ah, 0
add bx, ax
jmp read1
read3:
cmp cx, 0
jz read4
neg bx
read4:
mov ax, bx ;设置出口参数
pop dx
pop cx
pop bx
ret
read endp
;-----------------
;写数据
write proc
push ax
push bx
push dx
mov ax, wtemp
test ax, ax
jnz write1
mov dl, '0'
mov ah, 02
int 21h
jmp write5
write1:
jns write2
mov bx, ax
mov dl, '-'
mov ah, 02
int 21h
mov ax, bx
neg ax
write2:
mov bx, 10
push bx
write3:
cmp ax, 0
jz write4
sub dx, dx
div bx
add dl, 30h
push dx
jmp write3
write4:
pop dx
cmp dl, 10
je write5
mov ah, 02
int 21h
jmp write4
write5:
pop dx
pop bx
pop ax
ret
write endp
;-----------------
;光标回车换行的子程序
dpcrlf proc
push ax
push dx
mov ah, 2
mov dl, 0dh
int 21h
mov ah, 2
mov dl, 0ah
int 21h
pop dx
pop ax
ret
dpcrlf endp
;-----------------
;提示信息输出的子程序
print proc
push bp
mov bp, sp
push ax
push dx
mov si, [bp+4]
dsp1:
mov dl, [si]
cmp dl, 0
jz dsp2
mov ah, 02
int 21h
inc si
jmp dsp1
dsp2:
pop dx
pop ax
pop bp
ret
print endp
ends
end start ; set entry point and stop the assembler.