希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序;随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个文件恰被分成一组,算法便终止。
以下是汇编实现的代码:
S0 SEGMENT STACK
DW 20 DUP(?)
TOP LABEL WORD
S0 ENDS
S1 SEGMENT
TIP DB "Input ten number and separate the numbers with space:", 0DH, 0AH, 24H
ARY DW 20 DUP(0)
CRLF DB 0DH, 0AH, 24H
N DW 0
D DW 5
AD DW 10
E DW 0
S1 ENDS
S2 SEGMENT
ASSUME SS:S0, DS:S1, CS:S2, ES:S1
P PROC FAR
MOV AX, S0
MOV SS, AX
LEA SP, TOP
MOV AX, S1
MOV DS, AX
MOV AX, S1
MOV ES, AX
LEA DX, TIP
MOV AH, 9
INT 21H
LEA SI, ARY
XOR DX, DX
MOV BL, 10
MOV CX, 10
INPUT: MOV AH, 1
INT 21H
CMP AL, 20H ;空格分隔字符
JE SAVE
;输入十进制数,将数存入SI对应的内存单元
MOV DL, AL
MOV AX, [SI]
MUL BL
SUB DL, 30H
ADD AL, DL
MOV [SI], AX
JMP INPUT
SAVE:
ADD SI, 2
LOOP INPUT
;数组保存完毕
LEA SI, ARY
MOV DI, SI
ADD DI, 18
MOV E, DI ;数组末尾地址
MOV DI, SI
GO: MOV AX, D ;D表示增量,AD表示实际加的数
SHL AX, 1
MOV AD, AX ;假设增量为5,由于数组存储类型是DW,每次就需要加10
CMPA: ADD SI, AD
MOV AX, SI
SUB SI, AD
CMP AX, E ;判断加了增量后是否越界
JA CON
MOV BX, [SI] ;比较当前数与增量后的数
ADD SI, AD
MOV AX, [SI]
SUB SI, AD
CMP BX, AX
JA CHANGE
ADD SI, 2
JMP CMPA
CHANGE: ADD SI, AD ;交换两个数的位置
MOV AX, [SI]
SUB SI, AD
MOV [SI], AX
ADD SI, AD
MOV [SI], BX
SUB SI, AD
ADD SI, 2
CALL PRINT
JMP CMPA
CON: MOV AX, D
SHR AX, 1 ;增量除以2
MOV D, AX
MOV SI, DI ;从头开始
CMP AX, 0 ;增量为0时说明排序完成
JNE GO
EXIT: MOV AH, 4CH
INT 21H
P ENDP
;以下为十进制输出数组中的所有数
PRINT PROC NEAR
PUSH SI
PUSH CX
PUSH AX
PUSH DX
LEA DX, CRLF
MOV AH, 9
INT 21H
LEA SI, ARY
MOV CX, 10
L1: MOV AX, [SI]
MOV N, AX
CALL OUTPUT
ADD SI, 2
MOV DX, 20H
MOV AH, 2
INT 21H
LOOP L1
POP DX
POP AX
POP CX
POP SI
RET
PRINT ENDP
OUTPUT PROC NEAR
PUSH AX
PUSH BX
PUSH CX
PUSH DX
XOR CX, CX
MOV AX, N
MOV BX, 10
L2: XOR DX, DX
DIV BX
PUSH DX
INC CX
CMP AX, 0
JNE L2
L3: POP DX
ADD DX, 30H
MOV AH, 2
INT 21H
LOOP L3
POP DX
POP CX
POP BX
POP AX
RET
OUTPUT ENDP
S2 ENDS
END P
时间: 2024-11-03 18:08:17