10 November 2008

Bubblesort Multidimensional Array in Java

This quick work around will allow for an easy an "efficient" sort of a multidimensional array in Java. Simply pass your array in and the index you'd like to sort on.
Although there are other solutions to this, using java's builtin Arrays.sort method won't cut it. I put together this code to be called as a private method within your application. Enjoy!

This works great when using a String[][] compare. If you are trying to sort integers, simply change your array and take out the if (...compareTo...) business and just check which is greater.
private String[][] bubbleSortMulti(String[][] MultiIn, int compIdx) { String[][] temp = new String[MultiIn.length][MultiIn[0].length]; boolean finished = false; while (!finished) { finished = true; for (int i = 0; i < MultiIn.length - 1; i++) { if (MultiIn[i][compIdx].compareToIgnoreCase(MultiIn[i + 1][compIdx]) > 0) { for (int j = 0; j < MultiIn[i].length; j++) { temp[i][j] = MultiIn[i][j]; MultiIn[i][j] = MultiIn[i + 1][j]; MultiIn[i + 1][j] = temp[i][j]; } finished = false; } } } return MultiIn; }