Sorting Two Dimensional Arrays

Yesterday I wrote about how to sort ColdFusion arrays using the static sort() method on the java.util.Arrays object. The original question that inspired the post was actually about sorting 2-dimensional arrays. The answer is that you can sort 2-dimensional arrays using the technique I wrote about yesterday, but only in one dimension.

A ColdFusion 2-dimensional array is actually a java.util.Vector of java.util.Vectors. In other words, if you think of a 2-dimensional array as a table, the rows are Vectors, but the columns are not. If you take a slice of data in any particular column, none of the data is actually in the same data structure because the data actually spans as many Vectors as rows in your column. Maybe a diagram will help:

Array #1: [1][1] [1][2] [1][3] [1][4]
Array #2: [2][1] [2][2] [2][3] [2][4]
Array #3: [3][1] [3][2] [3][3] [3][4]
Array #4: [4][1] [4][2] [4][3] [4][4]

So as you can see, if you want to sort your 2-dimensional array horizontally, you are in luck, but if you want to sort it “by column”, or vertically, I think you will have to massage the data quite a bit first. Probably better to build a query object than a 2-dimensional array, in that case.

4 Responses to Sorting Two Dimensional Arrays

  1. Scott Keene says:

    I concede this argument to reason!

  2. Ernesto Piloto says:

    This is referred to the case you want to sort the 2-dimension array by column.Let’s say you have implemented a method to transpose the bi-dimensional array or matrix which can be possible in a linear order adding no considerable cost to the original sorting method. This should lead us to a new array that can easily be sortered and then transposed again to obtain the original one.Total Cost = Transpose Cost (lineal) + Sorting Method Cost + Transpose Cost (lineal)

  3. Casey Priest says:

    Do you have a diagram for a 3-dimensional array? I am having trouble populated a 3-dimensional array and I can’t seem to find anything on the web. Thanks

  4. Manish Paliwal says:

    This urgent requirement for my project.