Search code examples
assemblymasmbubble-sortemu8086

MASM611 - Bubble Sort giving unexpected output


I want to sort the following numbers using bubble sort in MASM611:

59H, 39H, 51H, 57H, 24H, 86H, 95H, 93H, 15H, 75H, 42H, 68H, 03H, 06H, 01H

The code I have written works well for all hexadecimal numbers less than 80. But if the array has even one number greater than 80H then it is placed in the beginning.

Can someone point out my mistake or give any solution to this weird behaviour. PS: I'm new to assembly.

Code:

ASSUME CS:CODE, DS:DATA

DATA SEGMENT
    ORG 1200H
    ARRAY DB 59H, 39H, 51H, 57H, 24H, 86H, 95H, 93H, 15H, 75H, 42H, 68H, 03H, 06H, 01H
    count equ 15
DATA ENDS

CODE SEGMENT
START:
    MOV AX, DATA
    MOV DS, AX

    MOV DX, COUNT-1
    OLOOP:
        MOV CX, COUNT-1
        LEA SI, ARRAY

        ILOOP:
            MOV AL, [SI]
            CMP AL, [SI+1]
            JL KEEP
            XCHG AL, [SI+1]
            MOV [SI], AL

            KEEP:
                INC SI
                LOOP ILOOP

        DEC DX
        JNZ OLOOP

HLT
CODE ENDS
END START

Debug:

enter image description here enter image description here

When array has hexadecimal numbers greater than 80:

The numbers which are greater than 80H have been placed before 01H (but the three numbers 86H, 93H, 95H are still in ascending order).

enter image description here

When array have hexadecimal numbers less than 80:

When there are no hexadecimal numbers in the array the output is as expected.

enter image description here


Solution

  • ARRAY DB 59H, 39H, 51H, 57H, 24H, 86H, 95H, 93H, 15H, 75H, 42H, 68H, 03H, 06H, 01H
    

    When dealing with this array of bytes, you have to decide how these bytes need to be interpreted.
    You can deal with them in the unsigned manner where their values will range from 0 to 255, or you can deal with them in the signed manner where their values will range from -128 to +127. Your code snippet uses the jl (JumpOnLess) instruction which tells us that you (knowingly?) prefer the signed manner. Because values like 86h, 95h, and 93h represents negative numbers (when viewed as signed numbers), this ascending sort will place these first.

    If you wish to sort an array of unsigned numbers then just use the jb (JumpOnBelow) instruction.


    One optimization for your BubbleSort

    The inner loop can start from an ever smaller counter because the last element from the current iteration will have reached its final destination.

    Change:

    OLOOP:
        MOV CX, COUNT-1
    

    into

    OLOOP:
        MOV CX, DX