Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting arrays in Java

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.

like image 576
Pranav Avatar asked Jul 05 '26 04:07

Pranav


2 Answers

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.

like image 183
Matthew Flaschen Avatar answered Jul 07 '26 17:07

Matthew Flaschen


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.

like image 41
mmx Avatar answered Jul 07 '26 16:07

mmx