Praveen Kumar Reddy Mora Praveen Kumar Reddy Mora - 5 months ago 28
Java Question

Swap rows in 2d array by row sum in Java

I implemented this thing but I am not sure this is correct

Example : int [][]={{2,1,0},{2,8,9},{1,1,0}}


In the above sum of elements in row
1 (2+1+0=3)
is lesser than sum of elements in row
2(2+8+9=19)
and greater than row 3 sum(2).

The final array should be like
{{2,8,9},{2,1,0},{1,1,0}}


int arr[5][5];
int rowSum[5];
int sum = 0;
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
sum = sum + arr[i][j];
}
rowSum[i] = sum;
sum=0;
}

int swap;
//now sorting
for (int c = 0 ; c < ( n - 1 ); c++)
{
for (int d = 0 ; d < n - c - 1; d++)
{
if (rowSum[d] > rowSum[d+1]) /* For decreasing order use < */
{
swap = rowSum[d];
rowSum[d] = rowSum[d+1];
rowSum[d+1] = swap;

//swapping original array
for(int i=0;i<5;i++){
swap = arr[d][i];
arr[d][i] = arr[d+1][i];
arr[d+1][i] = swap;
}
}
}
}

Answer

Use the below Code Snippet,

        int[][] temp = {{2,1,0},{2,8,9},{1,1,0}};
        Arrays.sort(temp, new Comparator<int[]>() {
        @Override
        public int compare(int[] a, int[] b) {
            return Integer.compare(b[1], a[1]);
        }
        });
        System.out.println("After applying comparator");
        for(int[] arr:temp){
            for(int val:arr){
                System.out.print(val+" ");
            }
            System.out.println("");
        }

It will display the output like this,

After applying comparator
2 8 9 
2 1 0 
1 1 0