Hi,
Quite a no of times when i am participating in the contests, i come across the problem where i have to sort 2 or 3 arrays according to a condition applied only on one of them .
For eg :
Cordinates of a point in 3d space are given as (x,y,z)
Now the input comes as (X[], Y[], Z[] .... are different arrays)
Quite a no of times when i am participating in the contests, i come across the problem where i have to sort 2 or 3 arrays according to a condition applied only on one of them .
For eg :
Cordinates of a point in 3d space are given as (x,y,z)
Now the input comes as (X[], Y[], Z[] .... are different arrays)
Now suppose i want to sort the co-ordinates in the ascending order of the x co-ordinate. Obviously i have to sort y and z accordingly too , preserving the relative position ....X[j] Y[j] Z[j]j
0 7 2 1
1 3 2 5
2 4 9 2
3 5 4 3
4 5 3 3
.. .. .. ..
.. .. .. ..
1000 terms
Is there any easy way to do it (maybe using library function ... preferably in java).. ?? Or do i have to go for simultaneous bubble sort or some other sort every time ...??
You can use STL sort from <algorithm>. It's more comfortable, than C analog.
The simple way to do this is to introduce something like Point class containing all three co-ordinates and implementing Comparable interface. Then you can declare array of Points and pass it to Arrays.sort. The other way is to use index array of 0..N and custom comparator comparing x[i] and x[j] , then access x, y, and z elements via this index array. Both approaches are kind of expensive, especially the first one where many litle objects are created in the heap.
P.S. @imslavako : m not good at c++ right now and i dont use it in most of my solution( i cant remember why ??? :) ) ... but still i will try it . thanks buddy
And if you need only 2 int coordinates, you can use java.awt.Point
UPD: or java.awt.geom.Point2D.Double for 2 double coordinates
But there is interface java.util.Map.Entry<K, V> and its implementation: class java.util.AbstractMap.SimpleEntry<K, V>. I don't use them because their fields are private and I don't want to call getters and setters. UPD: And key is final, and you aren't allowed to set it...
Maybe Egor's plugin contains something like Pair?