Hi, I am using a bubble sort algorithm to sort a 2D array. The array is as follows:

Code :

String data[][] = {{"John", "Smith", "14.75", "30", "ZZZZ", "ZZZZ", "ZZZZ",},{"Bill", "Gates", "18.50", "40","ZZZZ", "ZZZZ", "ZZZZ",}, {"Steve","Jobs", "10.75", "25","ZZZZ", "ZZZZ", "ZZZZ",},{"Paul", "Allen","21.50","34","ZZZZ", "ZZZZ", "ZZZZ",}, {"Steve", "Ballmer", "18.75", "35","ZZZZ", "ZZZZ", "ZZZZ",},{"ZZZZ", "ZZZZ", "ZZZZ", "ZZZZ"}}; //ZZZZ are marker values,the last row is to hold total values of all employees

I want to sort this 2D array by comparing last names (index 1), and bubble sorting all their corresponding values along with it.

Code :

static public String[][] sort(String data[][]) { for(int x = 0; x <= data.length-1; x++) { for(int y = 0; y<=data.length-2;y++) { if(data[y][1].compareTo(data[y+1][1]) > 0) //compare lastnames alphabetically { String temp = data[y][1]; //swap last names data[y][1]=data[y+1][1]; data[y+1][1] = temp; String temp2 = data[y][0]; //swap first names data[y][0]=data[y+1][0]; data[y+1][0] = temp2; String temp3 = data[y][2]; //etc data[y][2]=data[y+1][2]; data[y+1][2] = temp3; String temp4 = data[y][3]; data[y][3]=data[y+1][3]; data[y+1][3] = temp4; String temp5 = data[y][4]; data[y][4]=data[y+1][4]; data[y+1][4] = temp5; String temp6 = data[y][5]; data[y][5]=data[y+1][5]; data[y+1][5] = temp6; } } }

It compiles but when I run it i get the error:

java.lang.ArrayIndexOutOfBoundsException: 4