|
Re: Help!! Sorting two dimensional array.
|
Posted: Jun 24, 2003 11:44 AM
|
|
> Ok, this is what i have to do. I have abbreviations in > a[0][0] to a[n][0], and the full descriptions in a[0][1] > to a[n][1]. I need the first column sorted in ascending > order and have the second column arranged so that I still > have the correct corresponding description. > > I've used Arrays.sort(arrayname) on one-dimensional > arrays, tried to use it here but it didn't work. > > Do I have to write my own sort routine to get this done or > is there an easier way? > > Thanks.
This might sound a bit convoluted at first, but it should beat writing your own sort algorithm, in which you would have to keep track of both elements anyway.
Create a new array whose entries are the value of a[x][0] followed by the index at which they are located. For example, consider the following
arr[0][0] = "stncrb", arr[0][1] = "stone crab claws" arr[1][0] = "mt", arr[1][1] = "mai tai" arr[2][0] = "klp", arr[2][1] = "key lime pie"
Your sort array would contain the values as follows: sort[0] = "stncrb_001" sort[1] = "mt_002" sort[2] = "klp_003"
Then sort that 1d array and get sort[0] = "klp_003" sort[1] = "mt_002" sort[2] = "stncrb_001"
Go through that array and use the stored index to get the correct value out of the original array. So you would read sort[0], see that index 3 was what you were after and that would be your first sorted entry. You would end up with final[0][0] = "klp", final[0][1]= "key lime pie" final[1][0] = "mt", final[1][1] = "mai tai" final[2][0] = "stncrb", final[2][1] = "stone crab claws"
It isn't the fastest performing algorithm, but it's pretty short, easy to code and debug, and can be easily extended for varying sized arrays, assuming you're only ever sorting on one index. If you need to do this sort often, then this probably isn't the way you should go unless you'll be working with a small set of inputs most of the time. If the sort only happens occasionally or the input set is small, then this should do the trick with very little work on your part.
I'm sure plenty of people can easily complain about the memory explosion something like this will cause, but not knowing the scope of your problem, I'll leave the more efficient solution to others. This definitely falls under the quick and dirty category, but I've used little one-shot algorithms like this a lot.
|
|