COMMENT |         Bubble sort procedure     BBLSORTA.ASM
	Objective: To implement the bubble sort algorithm
	   Inputs: A pointer to the array to be sorted
		   and its size are received via the stack.
	   Output: Returns nothing but the array is sorted
|                  in ascending order.
SORTED    EQU   0
UNSORTED  EQU   1

.MODEL SMALL
.CODE
.486
PUBLIC _bubble_sort
_bubble_sort    PROC
	; save registers used by the procedure
	pusha
	mov     BP,SP
	
	;CX serves the same purpose as the end_index variable
	; in the C procedure. CX keeps the number of comparisons
	; to be done in each pass. Note that CX is decremented
	; by 1 after each pass.
	mov     CX, [BP+20]  ; load array size into CX
	mov     BX, [BP+18]  ; load array address into BX

next_pass:
	dec     CX           ; if # of comparisons is zero
	jz      done         ; then we are done
	mov     DI,CX        ; else start another pass

	;DX is used to keep SORTED/UNSORTED status
	mov     DX,SORTED    ; set status to SORTED

	;SI points to element X and SI+2 to the next element
	mov     SI,BX   ; load array address into SI
pass:
	;This loop represents one pass of the algorithm.
	;Each iteration compares elements at [SI] and [SI+2]
	; and swaps them if ([SI]) < ([SI+2]).
	mov     AX,[SI]
	cmp     AX,[SI+2]
	jg      swap
increment:
	;Increment SI by 2 to point to the next element
	add     SI,2
	dec     DI
	jnz     pass 
	
	cmp     DX,SORTED       ; if status remains SORTED
	je      done            ; then sorting is done
	jmp     SHORT next_pass ; else initiate another pass

swap:
	; swap elements at [SI] and [SI+2]
	xchg    AX,[SI+2]
	mov     [SI],AX
	mov     DX,UNSORTED     ; set status to UNSORTED
	jmp     SHORT increment       

done:
	; restore registers 
	popa     
	ret
_bubble_sort    ENDP
	END
