Sort a multidimensional array

czeslaw1

Member
Joined
May 18, 2009
Messages
18
Programming Experience
Beginner
Hi! I was looking for a function I need in internet but I didn't find it... I need to sort a multidimensional array(matrix).. for example
Original matrix
1,b,3
2,c,5
3,a,1

I need a function, lets call it magic() xD with 2 arguments, the matrix and which col to sort first...
so..
the result of magic(originalmatrix,1) could be..
3,a,1
1,b,3
2,c,5

Do you understand me? xD .. sorry I'm a beginner... How can I make it ? The matrix.sort doesn't help me with that.. i guess..
Thank you very much!! ^^ :D
 
There is no such function, unless someone writes one. That someone should probably be you. You should start by writing a method to sort a standard 1D array using whatever sorting algorithm you like. Once that's working, you can extend that to work with a 2D array. You can use the "column" index passed in to decide which values from each "row" to compare and then simply move all elements in a "row" instead of one element.

That said, if this isn't a learning exercise (in which case you should definitely be writing your own code) then you almost certainly shouldn't be using a 2D array anyway. Generally speaking, it's far better to first define a type that represents a "row" and then create a 1D array of instances of that type. For sorting such an array, follow the Blog link in my signature and check out my three-part submission on the topic.
 
Back
Top