java - Sort subarrays according to their first element -
i have array of objects, let's each object of type grid.
each grid object has x , y coordinates,
grid temp = new grid(3, 5); // temp.x returns x, temp.y returns y.
now have few arrays of grid
grid[] thearray1 = new grid[5]; grid[] thearray2 = new grid[5]; grid[] thearray3 = new grid[5];
i fill arrays grid objects , sort them using arrays.sort.
i join sorted arrays form thearray length 5+5+5=15.
i want sort thearray first element of "subarrays" (elements 0, 5 , 10 in thearray)
how achive this? also, if there simpler way achieve same result, nice. have start 3 arrays since gotten through iteration of for-loop.
edit:
example: let's sort x coordinated, smaller first. i'll make each grid[] of length 3 instead of 5 simplicity.
grid[] thearray1 = new grid[]{new grid(2, 1), new grid(4, 1), new grid(0, 1)}; grid[] thearray2 = new grid[]{new grid(4, 2), new grid(3, 1), new grid(7, 1)}; grid[] thearray3 = new grid[]{new grid(1, 7), new grid(5, 3), new grid(10, 1)};
what want end array/arraylist that, when printed, prints this:
for (int = 0; <= thearray.length-2; i++) { stdout.println(thearray[i] + ", " + thearray[i+1] + ", " + thearray[i+2] + "\n"); } // output: (0, 1), (2, 1), (4, 1) //this thearray1 (1, 7), (5, 3), (10, 1) //this thearray3 (3, 1), (4, 2), (7, 1) //this thearray2
first sort each thearray(1, 2 , 3) element lowest x coordinate first, second smallest, largest.
then arrange these arrays size of first element of each of them. thearray3 goes before thearray2 because x coordinate of first element 1 3 in thearray2
assuming grid
implements comparable<grid>
, sort each array , add 2d-array. sort array of arrays of grids using arrays.sort(grid[][], gridarraycomparator)
, gridarraycomparator
looks example like:
class gridarraycomparator implements comparator<grid[]> { public int compare(grid[] grids1, grid[] grids2) { if (grids1.length > 0 && grids1.length > 0) { return grids1[0].compareto(grids2[0]); } else if (grids1.length > 0) { return 1; } else if (grids2.length > 0) { return -1; } else { return 0; } } }
then copy 2-d array 1-d array.
Comments
Post a Comment