;BUBBLE_2--G5_17
;Arranges the 16-bit elements of a list in the extra segment
;  in ascending order,using bubble sort.
;Inputs: ES:DI=Starting address of the list.
;  First location of the list=Length of the list (words)
;**********************************************************
data	segment			;define data segment
  save_cnt	dw	?
  start_addr	dw	?
data	ends
;***********************************************************
edata	segment
  list	dw	10,76,98,8,55,82,31,64,22,47,12
edata	ends
;***********************************************************
prognam segment			;define code segment
;----------------------------------------------------------
main	proc	far

	assume cs:prognam,ds:data,es:edata

	push	ds
	sub	ax,ax
	push	ax
;
	mov	ax,data		;initialize DS
	mov	ds,ax
	mov	ax,edata
	mov	es,ax
;
	lea	di,list
	call	bubble
	ret
main	endp
;-----------------------------------------------------
bubble	proc	near
	push	ds
	push	cx
	push	ax
	push	bx
;
	mov	start_addr,di	;save starting address 
			     	;  in memory
	mov	cx,es:[di]	;fetch element count N
	mov	save_cnt,cx	;  save this value in memory
init:	mov	bx,1		;exchange flag (BX)=1
	dec	save_cnt	;get ready for
				;  count-1 compares
	jz	sorted		;exit if save_cnt is 0
	mov	cx,save_cnt	;and load this count 
				;  into CX
	mov	di,start_addr	;load start address 
				;  into DI
next:	add	di,2		;address a data el.
	mov	ax,es:[di]	;  and load it into AX
	cmp	es:[di+2],ax	;is next el. < this el.?
	jae	cont		;no,go check next pair
	xchg	es:[di+2],ax	;yes,exchange 
	mov	es:[di],ax	;  these elements
	sub	bx,bx		;and make exchange flag 0
cont:	loop 	next		;process entire list
	cmp	bx,0		;any exchanges made?
	je	init		;if so,process list again
sorted:	mov	di,start_addr	;if not so,
;
	pop	bx
	pop	ax
	pop	cx
	pop	ds
	ret			;exit

bubble	endp			
;----------------------------------------------------------
prognam ends			;end of code segment
;**********************************************************
	end	main		;end assembly
