• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sorting an 2D object array  RSS feed

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I have an array of arrays, where the initial array just holds reference to other arrays of objects. How can I sort the array of objects?
[code]
public static void bubbleSort(<TypeOfObject>[][] anArray) {

// Initialize variables
int indexPass = 0;
int index, j = 0;
float exchange = 0;


// For loop to find value on left
for (indexPass = (anArray.length - 1); indexPass > 1; indexPass--) {
// For loop to find value on right
for (j = 0; j < 27; j++) {//27 b/c the're always 27 elements
for (index = 0; index < indexPass; index++) {
// If statement to compare left and right values
if (anArray[j][index] > anArray[j][index+1]) {
//exchange contents of array @ index and index +1
exchange = anArray[j][index];
anArray[j][index] = anArray[index+1];
anArray[j][index+1] = exchange;
} //end of if statement
} //end of for loop
} //end of for loop
}

return;
}
[code]
Would something like the above work for me?
I do not want to sort the the first anArray[j] part because they are refernces to arrays of objects.
I hope it makes sense!
thanks, needz
 
Ranch Hand
Posts: 488
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would suggest a couple things, but I may be understanding your code wrong to begin with so I hope this helps somewhat.

Couldn't you use a loop like the following:



Also, I wouldn't always assume the size to be 26 and have it hard coded. If the size will always be 26 at least put 26 into a field and use a variable so that if that should ever change you would only have to change the one line of code.

Personally, I hate arrays and traditional for loops... what are you storing and what is it for? I'm sure there is a collection that you could use to do it better, faster, easier.

Hope that helps somewhat.
 
Brian Legg
Ranch Hand
Posts: 488
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One more thing.

This: "if (anArray[j][index] > anArray[j][index+1])"

will not work in this case. Your array is holding some type of Object and the program is not going to know if one is greater than the other automatically. And since your method can take in any type of Object it could potentially try to compare 2 different types of Objects. you should really consider using one of the collection classes offered in java.util.* and pass it a Comparator on creation. Using this method the collection will automatically sort your Objects as you add them as long as they are mutually comparable. If you don't know what I mean check out the "Java Tutorials" about Comparator and Collection and you will see many tips.

GL
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!