Sorting a 2d array in Java?
Sorting a 2d array in Java?
I have to sort a 2d array:
int row=4;
int col=6;
int A[][]=new int [row][col];
With this info, I have to copy the components into a single array:
int B[][]=new int[24];
and sort it from highest to lowest, then copy it back into the 2d array.
so far, i have:import java.util.*;
import java.io.*;
import javax.swing.JOptionPane;
public class extraCredit{
public static void main (String [] args){
Scanner input= new Scanner(System.in);
int row=4;
int col=6;
int A[][]=new int [row][col];
int B[][]=new int[24];
int temp=0;
String out=”";
for(int i=0; i
}
}
//print original array
for(int i=0; i
}
out+= “\n”;
}
System.out.print(out);
for(int k=0; k
}
I’m not sure how to finish it..
** I need to do this only using for loops and if statements .. without using the “.length” coding.
Under Forum

1 Comment for Sorting a 2d array in Java?
1. siamese_scythe | February 15th, 2011 at 8:21 am
Cross-reference:
http://answers.yahoo.com/question/index;_ylt=AtNwlhdDzW6_zxj9QE9gShbsy6IX;_ylv=3?qid=20101111065442AAFyqCM
So replace the .length with the actual lengths!!
http://ideone.com/TVuko
class sort2D {
public static void main(String[] args) {
int[][] testcase={{1,3,4,5,1,19}, {9,8,7,6,555,1}, {397,1,6,10,60,50}, {0,70,-1,555,12,11}};
printArr(testcase);
System.out.println();
sort(testcase);
printArr(testcase);
}
static void printArr(int[][] A) {
int i,j;
for(i=0;i<4;i++) {
for(j=0;j<6;j++)
System.out.print(A[i][j]+” “);
System.out.println();
}
}
static void sort(int[][] A) {
int i,j,B[]=new int[24];
for(i=0;i<4;i++)
for(j=0;j<6;j++)
B[i*6+j]=A[i][j];
java.util.Arrays.sort(B);
for(i=0;i<4;i++)
for(j=0;j<6;j++)
A[i][j]=B[i*6+j];
}
}
Leave a Comment for Sorting a 2d array in Java?
You must be logged in to post a comment.
Trackback this post | Subscribe to the comments via RSS Feed