'Pimp My Boxes' Contest

Blitz3D Forums/Blitz3D Programming/'Pimp My Boxes' Contest

I believe this is close to the fastest possible:
Function SortBoxes()

    cb.box = First box
    flag=True
    While flag
        flag=False
        cbb.box = Last box
        While cbb<>cb
            cbbb.box = Before cbb
            If cbbb=Null Then Exit
		
            If cbb\h>cbbb\h

				prea.box = Before cbb
				preb.box = Before cbbb
				If prea = Null
					Insert cbbb Before First box		
				Else
					Insert cbbb After prea
				EndIf
				
				If preb = Null
					Insert cbb Before First box		
				Else
					Insert cbb After preb
				EndIf

			    flag=True
            Else
                cbb=cbbb
            EndIf

        Wend
        cb=After cbb
    Wend

End Function

Function boxAlign()
	;Purpose: align boxes
	;Parameters: None
	;return: None
	
	SortBoxes()
	
	maxx = GraphicsWidth()
	maxy = GraphicsHeight()
	
	id = 0
	For box.box = Each box
		DebugLog box\w
		box2.box = After box
		If box2<>Null
			box2\x = box\x+box\w
			If box2\x+box2\w>maxx
				box2\x = 0
			EndIf
		EndIf
	Next

	For box.box = Each box
		Repeat
			;reset overlap counter and test against all boxes, except self
			boxesoverlap = False
			box2.box = First box
			While box2<>box
				If box<>box2
					If RectsOverlap(box\x,box\y,box\w,box\h,box2\x,box2\y,box2\w,box2\h) 
						box\y=box2\y+box2\h
						boxesoverlap = True
						Exit
					EndIf
				End If
				box2.box = After box2
			Wend
		Until Not boxesoverlap
	Next
	
End Function

But not always very effecient :) It's best with a large number of boxes, with little size variation.