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.
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.
When you pass an array to a function, it's not copied. Just the reference of it is copied and passed to the function which will point to the same location. You just need to sort the arrays in-place.
EDIT: To solve the actual sorting problem, you can use any sorting algorithm to sort height array. The only difference is that when you're swapping two elements in height sorting process, you should also swap the corresponding elements in weight array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With