The ArraySort function

The ArraySort function sorts the array in ascending or descending order depending on the value of the CL parameter.

Parameters: AX: pointer to the array; BX: array length; CL: sorting mode (ASCENDING or DESCENDING).

Return value: The function does not return a value.

Flag state: The function does not modify the flags.

Program source code

An example program for the Intel 8086 assembler demonstrating the use of the ArraySort function to sort an array in ascending or descending order.

title Author: Evgeny Sergeevich Dovgopolov

.model small
.stack 100h

data segment public
    array  dw  5, 5, 2, 6, 5, 10, 4, 2, 10, 0, 0, 1, 8, 2, 3, 9, 0, 7
    arrlen equ ($-array) / 2
    arrbuf dw  arrlen dup(0)
    fmtout db  "[%d] \0"
data ends

code segment public                ; Start of the code segment
    assume  ds:data, cs:code
    include Handyfar.inc           ; Include the file with functions
    include Handymac.inc           ; Include the file with macros

    main proc                      ; Start of the main procedure
        call    SetDataSegment     ; Call the SetDataSegment procedure

        mov     cx, arrlen         ; Copy the length of the array variable into the cx register
        lea     bx, es:[arrbuf]    ; Load the address of the variable arrbuf into the es:bx register
        lea     ax, ds:[array]     ; Load the address of the variable array into the ds:ax register
        call    ArrayMakeUnique    ; Call the ArrayMakeUnique procedure (ds:ax, es:bx, cx) := CX

        xchg    bx, cx             ; Exchange the values of the cx register and the bx register
        mov     cl, DESCENDING     ; Copy the DESCENDING value into the cl register
        lea     ax, ds:[arrbuf]    ; Load the address of the variable arrbuf into the ds:ax register
        call    ArraySort          ; Call the ArraySort procedure (ds:ax, bx, cl)

        lea     si, ds:[arrbuf]    ; Load the address of the variable arrbuf into the ds:si register

    PrintArrayLoop:
        push    word ptr[si]       ; 2nd: Save the si register value on the stack
        lea     ax, ds:[fmtout]    ; 1st: Load the address of the fmtout format string into the ds:ax register
        call    PrintFormatString  ; Call the PrintFormatString procedure
        add     sp, 2              ; Align the stack
        incw    si                 ; Call the incw macro. Increment the si index by 2
        loop    PrintArrayLoop     ; Loop while CX≠0

        xor     al, al             ; Clear the al register
        call    ExitProcess        ; Call the ExitProcess procedure
    main endp                      ; End of the main procedure

code ends                          ; End of the code segment
end main	                       ; End of file. The main procedure is the entry point

[10] [9] [8] [7] [6] [5] [4] [3] [2] [1] [0]

Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".