Thursday, April 26, 2012

Program to sort numbers in ascending order

; for that assume there are N words to be arranged

MY_DATA SEGMENT
    NUM_ARRAY DW 0100H, 0098H, 0012H, 0099H
    ; THE ARRAY OF N NUMBERS
    ARRAY_SIZE DW 0004H
    ; SIZE OF THE ARRAY
MY_DATA ENDS

CODE SEGMENT
    ASSUME CS:CODE, DS:MY_DATA
    ; THE TWO INITIALISATION STATEMENTS
    MOV AX, MY_DATA
    MOV DS, AX
   
    MOV DX, 2
    ; FOR SECONDS NUMBER THAT WILL GO ON INCREMENTING
   
FIRST:    MOV CX, DX
    DEC CX           
    ; THE FIRST NUMBER TO BE COMPARED WITH
    MOV SI, CX         ; STORE THIS IN SI
    ADD SI, SI

    MOV AX, NUM_ARRAY[SI]     ; GET THE NUMBER
   
BACK:    CMP NUM_ARRAY[SI-2], AX ; COMPARE THE 2 NUMBERS
    JBE NEXT        ; JUMP BELOW OR EQUAL
    MOV DI, NUM[SI-2]
    MOV NUM[SI], DI   
    ; PUT THE NUMBER IN THE CORRECT PLACE
    DEC SI
    DEC SI
    DEC CX
    JNZ BACK;
NEXT:     MOV NUM[SI], AX        ; PUT AX IN CORRECT POSITION
    INC DX
    CMP DX, ARRAY_SIZE    ; TO BE DONE FOR ALL NUMBERS IN AN ARRAY
    JBE FIRST        ; JUMP BELOW AND EQUAL FIRST
    HLT
    ; ARRAY SORTED IIN ASCENDING ORDER
; NOW SORT SAME ARRAY IN DESCENDING ORDER
    MOV CX, 2        ;{ARRAY_SIZE/2}
    MOV DX, ARRRAY_SIZE    ; INITIALISE DX
    MOV SI, 0000H        ; INITIALISE SI
; THE DESCEND BLOCK WILL JUST MOVE THE ARRANGED ARRAY IN REVERSE ORDER
DESCEND:MOV AX, NUM_ARRAY[DX]
    MOV BX, NUM_ARRAY[SI]
    MOV NUM_ARRAY[DX], BX
    MOV NUM_ARRAY[SI], AX
    INC SI
    DEC DX
    DEC CX
    JNZ DESCEND            HLT
; PROGRAM ENDS
CODE ENDS
END

No comments:

Post a Comment