;bblsort1.spt Simple bubble sort

;------------------------------------------------------------
;Test code

bArray		defByte		10

Test:
	LoadI		bArray	;Fill test array
	iSetMem		0,25
	iSetMem		1,17
	iSetMem		2,250
	iSetMem		3,2
	iSetMem		4,0
	iSetMem		5,5
	iSetMem		6,67
	iSetMem		7,76
	iSetMem		8,17
	iSetMem		9,14
	
	LoadX		bArray	;Prepare to sort
	LoadX		10
	GoSub		BblSort

Here	GoTo		Here

;------ Bubble sort -------------------------------------------------
;Sort an array of n values into ascending order (lowest first)
;Call with X = n)umber of values, Y=start of array
;Clobbers stack and I

;Note: This function could consume many mS of processor time depending on the array size.

sBBL_Swap		defSEM		;Notes a swap took place
bBBL_N:			defBYTE		;Array size
bBBL_Addr:		defBYTE		;Array address
bBBL_Count:		defBYTE		;Comparison counter

BblSort:
	Store		bBBL_N
	Store		bBBL_Addr

BBL_OuterLoop:
	ClrS		sBBL_Swap
	Recall		bBBL_Addr
	XtoI
	Recall		bBBL_N
	Store		bBBL_Count

BBL_InnerLoop:	;Back here to compare 1 pair of entries
	ClrInstCount			;For D>=18, inside a MultiTrack task
	iRecall		0		;Get two consecutive elements
	iRecall		1
	CompareR
	BranchR
	Target		BBL_Equal	;No swap
	Target		BBL_XGTY	;No swap
	Target		BBL_XLTY	;Swap

BBL_XLTY:
	iStore		0		;Save in swapped order
	iStore		1
	SetS		sBBL_Swap	
;Fall thru
BBL_Equal:
BBL_XGTY:
	IncI				;Array pointer
	DMGNZ		bBBL_Count,BBL_InnerLoop	;End of array?

;Done one scan. Test if any swaps were done
	GoIfST		sBBL_Swap,BBL_OuterLoop
	Return
