Quicksort - VBScript
2 Apr 2006
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
sortin 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
Compareproperty to a function reference to your sort function. To retreive a function reference in VBScript, pass the string name of the function toGetRef. - 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
anArrayin-place.
Sort Functions
A sort function should take two values a and b and return according to this chart:
| Condition | Result |
|---|---|
a < bor a sorts before b | CMP_LESS |
a > bor a sorts after b | CMP_GREATER |
a = bor a and b are equivalent | CMP_EQUAL |
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) nextOutput:
1,2,4,7,9
Sorting objects
To sort an array of objects, you must provide a custom sort routine.
class Thing
public int 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
- This code was derived from code online here.
Versions
- 1.1.1: Fixed bugs in the sample code, and in the "sort order" implementation.
Thanks to Charles Don Hall. - 1.1: Added sort order and API reference.
Contact Information
- Email:

