Complex number sort

I want to sort the complex vector as the lexicographically order, that is first the real part from large to small, the same real part, image part from small to large.

julia> a = ComplexF64[-0.05050274530206651 + 0.6013860908906193im, -0.050502745302066526 - 0.6013860908906193im, -1.1280686832693614 + 0.7017876343969567im, -1.1280686832693616 - 0.7017876343969567im]
4-element Vector{ComplexF64}:
  -0.05050274530206651 + 0.6013860908906193im
 -0.050502745302066526 - 0.6013860908906193im
   -1.1280686832693614 + 0.7017876343969567im
   -1.1280686832693616 - 0.7017876343969567im

julia> sort(a, by = x -> (real(x), -imag(x)), rev=true)
4-element Vector{ComplexF64}:
   -0.05050274530206651 + 0.6013860908906193im
   -0.050502745302066526 - 0.6013860908906193im
   -1.1280686832693614 + 0.7017876343969567im
   -1.1280686832693616 - 0.7017876343969567im

The -0.05050274530206651 and -0.050502745302066526 may consider the same value.
How to achieve the order

   -0.050502745302066526 - 0.6013860908906193im
   -0.05050274530206651 + 0.6013860908906193im
   -1.1280686832693616 - 0.7017876343969567im
   -1.1280686832693614 + 0.7017876343969567im
2 Likes

The -0.05050274530206651 and -0.050502745302066526 may consider the same value.

This is not quite clear, but probably you mean, that you want to compare values with less precision?

julia> sort(a, by = x -> (floor(real(x), digits = 6), -floor(imag(x), digits = 6)), rev=true)
4-element Vector{ComplexF64}:
 -0.050502745302066526 - 0.6013860908906193im
  -0.05050274530206651 + 0.6013860908906193im
   -1.1280686832693616 - 0.7017876343969567im
   -1.1280686832693614 + 0.7017876343969567im
1 Like

Some more information regarding your application would be useful. How do you obtain your vector to be sorted (this determines what kind of rounding errors we should expect), and for what purpose do you want to sort this vector according to the specified order (this might indicate suitable tolerances).

For the sake of discussion and information, I asked a quite close question on stack overflow a few months ago about finding the maximum / minimum value inside a complex array.

As far as I understood there, this will be base provided in Julia 1.7

julia - Generic maximum/minimum function for complex numbers - Stack Overflow