| Answer: |
You could simply write your own sort algorithm (like a bubble sort) and encapsulate it in a function, however there's another way that's faster, while remaining very flexible. The key is using the JScript array's highly efficient sort method. Since VBScript and JScript arrays aren't directly interchangeable, we have to incur some overhead passing them back and forth. But the overhead is usually worth it.
First we define a JScript function that accepts a VBArray (a safeArray type), changes it to a JScript array and sorts it:
<script language=JScript runat=server> function SortVBArray(arrVBArray) { return arrVBArray.toArray().sort().join('\b'); } </script> |
That's all there is to, it but here's the breakdown of the one line of code: return Tells the function to return whatever comes to the right of it as the output of the function.
arrVBArray.toArray() Calls the toArray() method of the VBArray to convert it to a JScript array (this method is only available in JScript).
.sort() Since the expression to the left of this code evaluates to a Jscript array, we can now call the sort() method of it, to perform a case-sensitive ascending sort.
.join('\b'); This now joins the JScript array into a delimited string. The '\b' is a special non-printable character that is used as the delimiter because it will (almost) never appear in a string unlike other potential delmiters such as the comma. This is how it will be passed back to VBScript.
Next you need a VBScript function to "finish off" what this function couldn't do in JScript, convert the output to a VBScript array. It looks like this:
<% Function SortArray(arrInput) SortArray = Split(SortVBArray(arrInput), Chr(8)) End Function %> |
Again only one line, this function uses the VBScript Split function to reconstitue the VBArray, now in sorted form. If you just wanted a sorted delimited string, you could call the SortVBArray() function directly.
The performance of this method is very good. Comparing executing time with a VBScript implementation of a bubble sort (shown below) gave the following results:
Array Size: 11 Items SortArray: < 10ms VB Bubble Sort: <10ms
Array Size: 211 Items SortArray: 10ms VB Bubble Sort: 160ms
Array Size: 1417 Items SortArray: 30ms (!) VB Bubble Sort: 7090ms
The larger the array, the more the savings with the .sort method. At 1417 items, it proves to be well over 200 times faster than even a very well implemented VB bubble sort!
VB bubble sort code:
<% for i = UBound(arrShort) - 1 To 0 Step -1 for j= 0 to i if arrShort(j)>arrShort(j+1) then temp=arrShort(j+1) arrShort(j+1)=arrShort(j) arrShort(j)=temp end if next next %> |
Happy Programming!
|