Sorting multi-dimensional arrays

Results 1 to 3 of 3

Thread: Sorting multi-dimensional arrays

  1. #1
    Shawn Kubik Guest

    Default Sorting multi-dimensional arrays

    Hi all,<BR><BR>I found some code on about sorting VBScript arrays by converting them to Javascript arrays, sorting them, and converting them back. It works fine on a single-dimensional array, but I&#039;m working with multidimensional arrays and would like to sort the array according to a single &#039;column&#039; in the array.<BR><BR>For example, I have an array defined like:<BR><BR>Dim myArray(5,2)<BR><BR>.. and I populate it with data. But then I want to sort it by the<BR>second column, so myArray(0,1), myArray(1,1), myArray(2,1), etc. would be sorted. Based on the code displayed on, I don&#039;t see how I would specifically reference that second &#039;column&#039;, and then, how to I convert it back into a multidimensional array using &#039;Split&#039;? I&#039;ve been using:<BR><BR>newArray = Split(sortArray(myArray), Chr(8))<BR><BR>Any ideas? Is there maybe a better way of doing this?<BR><BR>Thanks,<BR><BR>- Shawn Kubik.

  2. #2
    Join Date
    Dec 1969

    Default RE: Sorting multi-dimensional arrays

    JScript/JavaScript does not support multidimensional arrays... there is an article here on 4 guys somewhere that shows you how to sort 2d VBScript arrays. Check it out.

  3. #3
    Join Date
    Dec 1969

    Default But better answer: Don't do it!

    When you sort multi-dimensional arrays, you have to swap *all* the "inner" elements one at a time. Typically, that means you have an inner swapping loop nested inside the sort loop(s). That can be a *huge* time waster!<BR><BR>A better solution is to use an Array-of-arrays.<BR><BR>That is, instead of doing<BR><BR>Dim ar(5,2)<BR>ar(0,0) = x<BR>ar(0,1) = y<BR>ar(0,2) = z<BR>etc.<BR><BR>Do this:<BR><BR>Dim ar(5)<BR>ar(0) = Array(x,y,z)<BR>etc.<BR><BR>*NOW* you can swap entire *rows* of the array with just the classic three assignments (temp = ar(n) : ar(n) = ar(m) : ar(m) = temp)!<BR><BR>And, just incidentally, populating the array of arrays can be easily twice as fast as populating a 2d array.<BR><BR>Of course, if what you are doing is using RecordSet.GetRows to create the 2d array, then you have no choice. But if you are doing that, then you could sort the recordset *before* you create the array and it would be much more efficient.<BR><BR>

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts