sorting - How to sort a 2d array based on one row in java -
how sort 2d array using arrays.sort in java example array have
1 2 3 4; 8 2 4 9
sorted array should like
2 3 1 4; 2 4 8 9
sorting can done on basis of row. searched google , stack overflow of them giving answers sorting on basis of 1 column. tried writing comparator function failed. requirement wanted use both binarysearch function sort function of arrays.
as per example columns linked i.e. 1, 8
, 2, 2
, 3, 4
, 4, 9
, better create object linked data. putting them in object ensure stay together. check example sort based on column.
public class arraycolumnsortexample { public static void main(string[] args) { int rowsize = 2; arrayrow[] arr = new arrayrow[4]; arr[0] = new arrayrow(rowsize); arr[1] = new arrayrow(rowsize); arr[2] = new arrayrow(rowsize); arr[3] = new arrayrow(rowsize); arr[0].row[0] = 1; arr[0].row[1] = 8; arr[1].row[0] = 2; arr[1].row[1] = 2; arr[2].row[0] = 3; arr[2].row[1] = 4; arr[3].row[0] = 4; arr[3].row[1] = 9; for(int i=0; i<arr.length; i++){ for(int j=0; j<rowsize; j++) system.out.print(arr[i].row[j]+" "); system.out.println(); } arrayrow.sortcolumn = 0; //change value based on sorting requirement arrays.sort(arr); system.out.println(); for(int i=0; i<arr.length; i++){ for(int j=0; j<rowsize; j++) system.out.print(arr[i].row[j]+" "); system.out.println(); } } static class arrayrow implements comparable<arrayrow>{ integer[] row; static int sortcolumn; public arrayrow(int size) { this.row = new integer[size]; } @override public int compareto(arrayrow o) { return this.row[sortcolumn].compareto(o.row[sortcolumn]); } } }
apply optimization based on requirement.
Comments
Post a Comment