0

I am using Arrays.Sort() function in java to sort a names in 2D array storing names and corresponding numbers. I want number to remain in the same indices as to the corresponding names. How do I do it?

Thanks in advance.

CODE

String[][] contact = new String[3][3];
contact[0][0] = "b";
contact[0][1] = "c";
contact[0][2] = "a";
contact[1][0] = "2";
contact[1][1] = "3";
contact[1][2] = "1";
Arrays.sort(contact[0]);

Example:

b c a

2 3 1

OUTPUT:

a b c

2 3 1

I want to get:

a b c

1 2 3

5
  • Could you post the code you have tried? We need more information. How are you storing your arrays? Commented Jan 19, 2014 at 0:47
  • You are going to have to provide some code showing what your data structure looks like. It sounds like you want to sort one array and have a different array "follow along" based on the original positions in both arrays... but I could be wrong. Commented Jan 19, 2014 at 0:48
  • You are right @JimGarrison...That's exactly what I want, how do I do it?? Commented Jan 19, 2014 at 0:50
  • You probably can't user Arrays.sort for this data structure. Passing in contact[0] would mean it knows nothing about contact[1]. Would you consider making it a 1D array? Commented Jan 19, 2014 at 0:57
  • Yes, I am open to other solutions and how will that help? Commented Jan 19, 2014 at 0:57

2 Answers 2

2

Before you sort your array make a copy of it, then after sorting loop through the sorted one and use originalArray.indexOf(newArray[i]) to get the original index of the string, then set the new "index array"[i] to the value of the original index array[original index of the string].

You need to turn the original array into a list before you do this with Arrays.asList(originalArray).

Sign up to request clarification or add additional context in comments.

Comments

0
public class MatrixCell{

 private Integer x = 0;
 private Integer y = 0;
 private String name = "";

 public MatrixCell(int x, int y, String name){
   this.x = x;
   this.y = y;
   this.name = name;
 }

 //getters and setters
}

Then make an array of MatrixCell and done. Although this way you have to make too the sort algorithm.

3 Comments

No you're assuming that I'm assuming
I kind of agree with Eric here. If OP were to implement your answer they would have to rewrite a majority of their program versus implementing one of the million brute-force algorithms that can be used to sort a 2-D array.
@Tdorno I wrote the answer before the additional info provided by the OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.