汇编语言数据排序。提示输入数据,比如10个数据(十进制形式)然后,输入提示,1-从大到小排序;2-从小到大排序,显示按要求排序的数据。可以显示在同一行、两个数据之间用一定空格分开;也可以显示在不同的行。使masm可运行
时间: 2024-02-09 12:12:17 浏览: 58
以下是使用 x86 汇编语言实现从大到小排序的示例代码。该代码使用冒泡排序算法,可以输入最多 10 个数据,且每个数据必须是 32 位有符号整数。
```
.model small
.stack 100h
.data
prompt db "Please enter up to 10 integers: $"
sort_prompt db "Enter 1 to sort in descending order, or 2 to sort in ascending order: $"
sorted_data db "Sorted data: $"
space db " "
newline db 0Dh, 0Ah, "$"
data dw 10 dup (?)
sorted dw 10 dup (?)
.code
main proc
; Prompt for input
mov ah, 09h
lea dx, prompt
int 21h
; Read up to 10 integers
mov cx, 10
lea si, data
read_loop:
mov ah, 01h
int 21h
cmp al, 0Dh ; Check for Enter key
je done_reading
sub al, '0' ; Convert character to integer
mov [si], ax
add si, 2
loop read_loop
done_reading:
; Prompt for sorting order
mov ah, 09h
lea dx, sort_prompt
int 21h
; Read sorting order
mov ah, 01h
int 21h
sub al, '0'
; Sort data
mov si, offset data
mov di, offset sorted
mov cx, 10
outer_loop:
mov bx, si
mov dx, si
mov ax, [si]
inner_loop:
add dx, 2
cmp dx, offset data + cx * 2
jge next_iteration
mov bx, dx
mov ax, [dx]
cmp ax, [si]
jle inner_loop
mov [si], ax
mov ax, [dx]
mov [dx], [si]
mov [si], ax
jmp inner_loop
next_iteration:
mov [di], ax
add di, 2
add si, 2
loop outer_loop
; Output sorted data
mov ah, 09h
lea dx, sorted_data
int 21h
mov si, offset sorted
mov cx, 10
output_loop:
mov ax, [si]
push ax ; Save data for later use
mov ah, 02h
mov dl, ' '
int 21h
add si, 2
loop output_loop
; Output sorted data on separate lines
mov ah, 09h
lea dx, newline
int 21h
mov si, offset sorted
mov cx, 10
output_loop2:
pop ax ; Restore saved data
mov ah, 02h
mov dl, ' '
int 21h
mov ah, 02h
lea dx, newline
int 21h
add si, 2
loop output_loop2
; Exit program
mov ah, 4Ch
int 21h
main endp
end main
```
您可以使用 MASM 或 TASM 编译器将代码编译为可执行文件,例如:
```
masm sort.asm
link sort.obj
```
然后运行可执行文件:
```
sort.exe
```
阅读全文