Java – Sorting arrays in Java

arraysjavasorting

I want to pass 2 arrays to a function in Java and have them sorted in the calling function. How do i use a function to accomplish that?

I could have the function return an object with 2 arrays, but is there a non object-oriented solution to this?

EDIT : I this particular situation I cant use the inbuilt Array.sort function in Java. Lets say the 2 arrays are height and weight. They are of the same length, and the same index correspond to the same person's height and weight on both arrays. I want to sort the height array in ascending order, while sorting the weight array corresponding to the height array. So using the sort function would mess up the relations between the 2 arrays.

Best Solution

public void sort2(Object o1[], Object o2[])
{
  Arrays.sort(o1);
  Arrays.sort(o2);
}

Slightly more sophisticated:

public <T> void sort2(T o1[], T o2[],  Comparator<? super T> c)
{
  Arrays.sort(o1, c);
  Arrays.sort(o2, c);
}

EDIT: Generally, when you use parallel arrays, that means you are not using objects properly. To follow your example, you should have a Comparable Person class with height and weight properties. Of course, like Mehrdad said, you can manually implement a parallel array sorting algorithm, but it's really not ideal.