Home > Net >  How To Sort 2d array by column value with saving initial indexing
How To Sort 2d array by column value with saving initial indexing

Time:01-07

I am looking to sort the following array based on the values in first column with saving initial position of row in input 2D array.

int [][]intervals =
{
    {3,4},
    {2,3},
    {1,2},
};

Output Will be

{1,2,2}
{2,3,1}
{3,4,0}

Here third column is for initial Position of row in input 2D Array.

CodePudding user response:

You can levarage Arrays.sort and pass a Comparator accordingly. This will work in your case:

        int [][] intervals =
                {
                        {3,4},
                        {2,3},
                        {1,2},
                };

        int mRows = intervals.length;
        int nCols = intervals[0].length;

        int [][]intervalsNew = new int[mRows][nCols   1];

        for (int i = 0; i < mRows; i  ) {
            intervalsNew[i] = Arrays.copyOf(intervals[i], nCols   1);
            intervalsNew[i][nCols] = i;
        }

        Arrays.sort(intervalsNew, new Comparator<int[]>() {
            public int compare(int[] a, int[] b) {
                return Double.compare(a[1], b[1]);
            }
        });

        for (int i = 0; i < mRows; i  ) {
            System.out.println(Arrays.toString(intervalsNew[i]));
        }

Output:

[1, 2, 2]
[2, 3, 1]
[3, 4, 0]

CodePudding user response:

I had less knowledge than mantri about certain methods, hence I rely heavily on streams here, and the code is more verbose. Here is my attempt:

public class Intervals {

    public static void main(String[] args) {
    int[][] intervals = { { 3, 4 }, { 2, 3 }, { 1, 2 }, };

    // Convert to List to make easier to work on.
    List<List<Integer>> outer = new ArrayList<>();
    for (int[] x : intervals) {
        List<Integer> inner = new ArrayList<>();
        for (int y : x) {
        inner.add(y);
        }
        outer.add(inner);
    }

    // Create list of ints 0,1,2,3 to add to end.
    List<Integer> range = IntStream.rangeClosed(0, outer.size() - 1)
                                   .boxed()
                                   .collect(Collectors.toList());

    range.stream()
         .forEach(i -> {
             outer.get(i)
                  .add(i);
         });

    List<int[]> temp_new_intervals = new ArrayList<>();

    outer.stream()
         .sorted((c1, c2) -> {
             if (c1.get(0) > c2.get(0)) {
             return 1;
             } else if (c1.get(0) == c2.get(0)) {
             return 0;
             } else {
             return -1;
             }
         })
         .forEach(arr -> {
             // Because arr is Object [] we need to make it int[]
             Object[] objects = arr.toArray();
             int[] ints = Arrays.stream(objects)
                                .mapToInt(o -> (int) o)
                                .toArray();

             temp_new_intervals.add(ints);

         });

    int[][] new_intervals = new int[outer.size()][];

    for (int i = 0; i < outer.size(); i  ) {
        new_intervals[i] = temp_new_intervals.get(i);
    }

    for (int[] x : new_intervals) {
        System.out.println(Arrays.toString(x));
    }

    }

}

Output:

[1, 2, 2]
[2, 3, 1]
[3, 4, 0]
  •  Tags:  
  • Related