	
	.section    	.iwram,"ax"
	.align		4

@****************************************************************:
@*:
@*: qsort
@*:
@* in:	r0 = array
@*: 	r1 = left
@*: 	r2 = right
@**:	
@*:	r10 = &getcont
@*:	r11 = &swapcont
@*:
@*:
@*: waste not r7,r12
@*:
@*********************************************:

	.global	qsort
	.type	qsort,function
qsort:

	stmfd	sp!,{r5,r6,lr}

	cmp	r2,r1			@right<left
	ble	nSort2
	
	stmfd	sp!,{r1,r2}		@save l&r
	
	mov	r3,r1			@r3 (key) = getcont(r0 (array),r3 (left))@
	mov	lr,pc
	mov	pc,r10
	
	add	r4,r1,#1		@i=left+1	@r4=r1+1
	mov	r5,r2			@j=right	@r5=r2
	
loopA2:					@for(@@)

loopB2:					@for(@@)
	cmp	r4,r2			@if(i>=right) 	@if(r4>=r2) break@
	bge	loopB_e2
	
	mov	r6,r3			@save key (r6=r3)
	
	mov	r3,r4			@r3 = getcont(r0 (array),i (r4))
	mov	lr,pc
	mov	pc,r10
	
	cmp	r3,r6			@if(r3>r6) break@
	mov	r3,r6			@restore key
	blt	loopB_e2

	add	r4,r4,#1		@i++

	b	loopB2
loopB_e2:

loopC2:
	cmp	r5,r1			@if(j<=l) 	@r5<=r1	break
	ble	loopC_e2
	
	mov	r6,r3			@save key
	
	mov	r3,r5			@r3 = getcont(r0 (array),j (r5)) 
	mov	lr,pc
	mov	pc,r10
	
	cmp	r3,r6			@r3 < r6 (key) break@
	mov	r3,r6			@restore key
	bgt	loopC_e2
	
	sub	r5,r5,#1		@j--

	b	loopC2
loopC_e2:	

	cmp	r4,r5			@if( i (r4)>=j (r5) ) break@
	bge	loopA_e2

	
	mov	r8,r4			@i
	mov	r9,r5			@j	
	mov	lr,pc			@swapcont(array,i,array,j)@
	mov	pc,r11
	
	b	loopA2
loopA_e2:	

	mov	r8,r5			@j
	mov	r9,r1			@left
	mov	lr,pc			@swapcont(array,j,array,left)@
	mov	pc,r11
	
	ldmfd	sp!,{r1,r2}
	
	mov	r6,r2
	orr	r6,r6,r1, lsl #16
	
	sub	r2,r5,#1		@ quick_sort(array, left, j-1)@
	bl	qsort_back
	
	mov	r2,r6, lsl #16
	mov	r1,r6, lsr #16
	mov	r2,r2, lsr #16
	
	mov	r6,r2
	orr	r6,r6,r1, lsl #16
	
	add	r1,r5,#1
	bl	qsort_back		@ quick_sort(array, j+1, right)@
	
	mov	r2,r6, lsl #16
	mov	r1,r6, lsr #16
	mov	r2,r2, lsr #16

nSort2:	
	ldmfd	sp!,{r5,r6,lr}
	bx	lr