Non-recursive Quicksort Algorithm

BlitzMax Forums/BlitzMax Programming/Non-recursive Quicksort Algorithm

The forum is locked. These are the original blitzbasic.com forums, kept so they can still be read. No new topics, replies or edits can be made here. To join in, head over to the Blitz3D+ forums.

I found the algorithm I was originally looking for buried in a .rar on my hd. I'll use yours though, because it will probably be faster due to the use of insertion sorting on small lists. Here's the original code I was looking for translated to BMax anyway:

' *** QUICKSORT ***

NumMax = 5000000

Local Array [ NumMax ]
For i = 1 To NumMax - 1
	Array [ i ] = Rand ( 1 , 100000 )
Next

Local Stack1 [ 160 ]
Local Stack2 [ 160 ]

OldMillisecs = MilliSecs ( )

StackPtr = 0
HeadPtr = 1
TailPtr = NumMax-1

#Jump2

While HeadPtr < TailPtr

	Pivot = Array [ ( HeadPtr + TailPtr ) / 2 ]
	a = HeadPtr
	b = TailPtr
	
	#Jump1
	
	While Array [ a ] < Pivot
	
		a = a + 1
	
	Wend
	
	While Array [ b ] > Pivot
	
		b = b - 1
		
	Wend
	
	If a < b
	
		t = Array [ a ]
		Array [ a ] = Array [ b ]
		Array [ b ] = t
		a = a + 1
		b = b - 1
		Goto Jump1
		
	EndIf
	
	If a = b
	
		q = b - 1
		r = a + 1
	
	Else
	
		q = b
		r = a
		
	EndIf
	
	StackPtr = StackPtr + 1
	p = HeadPtr
	s = TailPtr
	
	If ( q - p ) < ( s - r )
	
		Stack1 [ StackPtr ] = r
		Stack2 [ StackPtr ] = s
		HeadPtr = p
		TailPtr = q
		
	Else
	
		Stack1 [ StackPtr ] = p
		Stack2 [ StackPtr ] = q
		HeadPtr = r
		TailPtr = s
		
	EndIf
	
Wend

If StackPtr > 0

	HeadPtr = Stack1 [ StackPtr ]
	TailPtr = Stack2 [ StackPtr ]
	StackPtr = StackPtr - 1
	Goto Jump2

EndIf

NewMillisecs# = MilliSecs ( ) - OldMillisecs
NewMillisecs# = NewMillisecs# / 1000.0
Print String ( NewMillisecs# ) + " Seconds"

For i = 1 To 10

	Print Array [ i ]

Next