使用汇编语言对选择排序的十个数字列表进行排序。 如何将此冒泡排序方法转换为选择排序方法
`[org 0x0100]
jmp start
data: dw 60, 55, 45, 50, 40, 35, 25, 30, 10, 0
swap: db 0
start: mov bx, 0 ; initialize array index to zero
mov byte [swap], 0 ; rest swap flag to no swaps
loop1: mov ax, [data+bx] ; load number in ax
cmp ax, [data+bx+2] ; compare with next number
jbe noswap ; no swap if already in order
mov dx, [data+bx+2] ; load second element in dx
mov [data+bx+2], ax ; store first number in second
mov [data+bx], dx ; store second number in first
mov byte [swap], 1 ; flag that a swap has been done
noswap: add bx, 2 ; advance bx to next index
cmp bx, 18 ; are we at last index
jne loop1 ; if not compare next two
cmp byte [swap], 1 ; check if a swap has been done
je start ; if yes make another pass
mov ax, 0x4c00 ; terminate program
int 0x21`
答案 0 :(得分:0)
这里的关键是改变你的循环。目前,它正在交换相邻的数字。您需要更改它以将最右边的元素复制到寄存器中,并将预先存在的已排序数组向右移动,直到刚移动的元素大于或等于刚刚复制到寄存器中的最右边元素。
答案 1 :(得分:0)
也许这会有所帮助。我很久以前写过这篇文章。 Realmode intel汇编程序。
MAIN.ASM
SSTACK SEGMENT PARA STACK 'STACK'
DW 128 DUP(?)
SSTACK ENDS
DSEG SEGMENT PUBLIC 'DATA'
S LABEL BYTE
ARR DB 'IHGFED27182392JASKD1O12312345CBA'
LEN EQU ($-S)
PUBLIC TMP
PUBLIC MIN
TMP DW ?
MIN DW ?
DSEG ENDS
CSEG SEGMENT 'CODE'
ASSUME CS:CSEG, SS:SSTACK, DS:DSEG
EXTRN OUTPUT:NEAR
EXTRN SORT:NEAR
START: MOV AX, DSEG
MOV DS, AX
MOV BX, OFFSET ARR
MOV CX, LEN
CALL OUTPUT
MOV AX, 60
CMP AX, 0
JZ NO_SORT
CMP AX, 1
JZ NO_SORT
MOV BX, OFFSET ARR
MOV CX, LEN
CALL SORT
NO_SORT: MOV BX, OFFSET ARR
MOV CX, LEN
CALL OUTPUT
MOV AH, 4CH
MOV AL, 0
INT 21H
CSEG ENDS
END START
SORT.ASM
DSEG SEGMENT PUBLIC 'DATA'
EXTRN TMP:WORD
EXTRN MIN:WORD
DSEG ENDS
CSEG SEGMENT 'CODE'
ASSUME CS:CSEG, DS:DSEG
PUBLIC SORT
SORT PROC; (AX - N, BX - ARRAY ADDRESS, CX - ARRAY LENGTH)
PUSH SI
PUSH DI
PUSH DX
CALL COMPARE_MIN
DEC CX
MOV AX, CX
XOR SI, SI
XOR DI, DI
L1:
PUSH CX
MOV MIN, SI
MOV TMP, DI
INC DI
MOV CX, AX
L2:
MOV DH, BYTE PTR[BX+DI]
PUSH SI
MOV SI, MIN
MOV DL, BYTE PTR[BX+SI]
POP SI
CMP DH, DL
JA OLD_MIN
NEW_MIN: MOV MIN, DI
OLD_MIN: INC DI
DEC CX
CMP CX, TMP
JNZ L2
SWAP: PUSH DI
MOV DI, MIN
MOV DL, BYTE PTR[BX+DI]
MOV DH, BYTE PTR[BX+SI]
MOV BYTE PTR [BX+SI], DL
MOV BYTE PTR [BX+DI], DH
POP DI
INC SI
MOV DI, SI
POP CX
LOOP L1
POP DX
POP DI
POP DI
RET
SORT ENDP
COMPARE_MIN PROC; (AX - A, CX - B CX - MIN)
PUSH AX
CMP AX, CX
JB B__A
JA A__B
A__B: MOV CX, CX
JMP EX
B__A: MOV CX, AX
JMP EX
EX: POP AX
RET
COMPARE_MIN ENDP
CSEG ENDS
END
OUTPUT.ASM
CSEG SEGMENT 'CODE'
ASSUME CS:CSEG
PUBLIC OUTPUT
OUTPUT PROC ; (BX - ARRAY ADDRESS, CX - ARRAY LENGTH)
PUSH DX
PUSH SI
PUSH AX
XOR SI, SI
MOV AH, 02H
OUTARR: MOV DL,[BX+SI]
INT 21H
INC SI
LOOP OUTARR
MOV DL, 10
INT 21H
POP AX
POP SI
POP DX
RET
OUTPUT ENDP
CSEG ENDS
END