汇编冒泡排序问题求助:swapByRef过程无法交换数组元素
Hey there! Let's dig into why your bubble sort assembly code isn't working. I spotted a few key issues that are throwing off the logic—let's break them down one by one:
Key Issues in Your Code
Incorrect array index increment
Your array usesdw(2-byte words), so each element takes up 2 bytes. But you're usinginc bxto move to the next element—this only increments the offset by 1 byte, meaning you're actually accessing the high/low bytes of the same element instead of the next one. You need to add 2 tobxwithadd bx, 2instead.Wrong comparison operation
You load the current element intoaxand the next intodx, but then compareal(low byte of the current element) toah(high byte of the current element) withcmp al, ah. That's comparing parts of the same value, not the two adjacent elements you want to sort. Usecmp ax, dxto compare the full 2-byte values instead.Mismatched loop termination condition
Yoursortingloop checks ifbxequalsax(whereaxislen - 1). Butbxis a byte offset, whileaxis an element count. For example, with 5 elements,len - 1is 4, but the last valid byte offset for the penultimate element is 8 (since each element is 2 bytes: 0, 2, 4, 6, 8). Convert the element count to a byte offset by multiplyingaxby 2 before comparing tobx.Invalid syntax with
offsetoffset [ARR + bx]isn't valid MASM syntax. Sincebxalready holds the offset of the current element, you can pushbxdirectly for the current element's address, andbx + 2for the next element.
Fixed Bubble Sort Code
Here's the corrected version with all issues addressed:
MODEL small STACK 100h DATA SEGMENT ARR dw 9,5,7,3,8 len dw 5 DATA ENDS CODE SEGMENT ASSUME CS:CODE, DS:DATA start: mov ax, DATA mov ds, ax xor bx, bx ; Initialize index to start of array sorting: mov ax, len dec ax shl ax, 1 ; Multiply by 2 to convert element count to byte offset cmp bx, ax je redo mov ax, ARR[bx] mov dx, ARR[bx + 2] cmp ax, dx ; Compare full 2-byte values jg swap jmp continue swap: push bx ; Push address of current element push bx + 2 ; Push address of next element call swapByRef continue: add bx, 2 ; Move to next 2-byte element jmp sorting redo: mov ax, len dec ax mov len, ax cmp len, 0 ; Exit if no more elements to sort je exit xor bx, bx ; Reset index to start of array jmp sorting exit: mov ax, 4c00h int 21h swapByRef proc mov bp, sp mov bx, [bp + 2] mov ax, [bx] mov si, [bp + 4] mov cx, [si] mov [bx], cx mov [si], ax ret 4 swapByRef endP CODE ENDS END start
Quick Fix Recap
- We use
add bx, 2to step through each 2-byte element in the array. - The comparison now uses
cmp ax, dxto compare full element values. shl ax, 1converts the element count to a byte offset, making the loop termination check valid.- We push register values directly instead of invalid
offsetsyntax, sincebxalready holds the correct element offset.
This should correctly sort your array using your existing swapByRef procedure.
内容的提问来源于stack exchange,提问作者Yoav Linder

