Projects » VBScript » Quicksort

Quicksort - VBScript

29 Mar 2009
Version: 1.2
Download: qsort.vbs
View on GitHub

A Quicksort class for VBScript that can handle arrays of values or objects.

This QSort class can sort arrays of values (strings, numbers) or objects.

API Reference

Quicksort class

dim sort
set sort = new QSort
Create a new Quicksort object. (You may use any name for this object; it will be called sort in the rest of this documentation.)
set sort.Compare = GetRef("sort_function")
To sort an array of objects, a custom sort function must be specified. Set the Compare property to a function reference to your sort function. To retreive a function reference in VBScript, pass the string name of the function to GetRef.
sort.Order = ORDER_ASC (default)
sort.Order = ORDER_DESC
Set the sort order to ascending (lower values sort first, default) or descending (lower values sort last).
sort.Sort anArray
Sorts anArray in-place.

Sort Functions

A sort function should take two values a and b and return according to this chart:

Condition Result
a < b
or
a sorts before b
CMP_LESS (-1)
a > b
or
a sorts after b
CMP_GREATER (1)
a = b
or
a and b are equivalent
CMP_EQUAL (0)

Examples

Sorting values

To sort an array of values, nothing special needs to be done.

dim a
a = Array(4,1,9,2,7)

dim sort
set sort = new QSort
sort.Sort a

dim i
for i = 0 to UBound(a)
   if (i > 0) then Response.Write ","
   Response.Write a(i)
next
Output:
1,2,4,7,9

Sorting objects

To sort an array of objects, you must provide a custom sort routine.

class Thing
	public a
end class

function make_thing(value)
	dim t : set t = new Thing
	t.a = value
	set make_thing = t
end function

function cmp_thing(a, b)
	if (a.a < b.a) then
		cmp_thing = CMP_LESS
	elseif (a.a > b.a) then
		cmp_thing = CMP_GREATER
	else
		cmp_thing = CMP_EQUAL
	end if
end function

dim a
a = Array(make_thing(4),make_thing(1),make_thing(9),make_thing(2),make_thing(7))

dim sort
set sort = new QSort
set sort.Compare = GetRef("cmp_thing")
sort.Sort a

dim i
for i = 0 to UBound(a)
   if (i > 0) then Response.Write ","
   Response.Write a(i).a
next
Output:
1,2,4,7,9

References

Product Links

Versions


Contact Information