w3resource

NumPy: Sort a given complex array using the real part first, then the imaginary part


6. Sort Complex Array by Real then Imaginary Part

Write a NumPy program to sort a given complex array using the real part first, then the imaginary part.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating a list of complex numbers
complex_num = [1 + 2j, 3 - 1j, 3 - 2j, 4 - 3j, 3 + 5j]

# Displaying the original array of complex numbers
print("Original array:")
print(complex_num)

# Sorting the given complex array using the real part first, then the imaginary part
print("\nSorted a given complex array using the real part first, then the imaginary part.")
print(np.sort_complex(complex_num)) 

Sample Output:

Original array:
[(1+2j), (3-1j), (3-2j), (4-3j), (3+5j)]

Sorted a given complex array using the real part first, then the imaginary part.
[1.+2.j 3.-2.j 3.-1.j 3.+5.j 4.-3.j]

Explanation:

In the above exercise –

complex_num = [1 + 2j, 3 - 1j, 3 - 2j, 4 - 3j, 3 + 5j]: This line creates a list complex_num containing five complex numbers.

print(np.sort_complex(complex_num)): This line uses the np.sort_complex function to sort the list complex_num in ascending order. The sorting is based on the real parts first, and in case of equal real parts, the imaginary parts are considered. In this case, the sorted complex numbers are [1 + 2j, 3 - 2j, 3 - 1j, 3 + 5j, 4 - 3j].

For more Practice: Solve these Related Problems:

  • Sort a complex array by its real parts first and, for equal real parts, by the imaginary parts using np.argsort on a compound key.
  • Create a function that returns the sorted complex array and ensures stability in the ordering of imaginary parts.
  • Implement a solution that separates the real and imaginary parts, sorts them independently, and recombines the complex numbers.
  • Test the function on arrays where several complex numbers share the same real part to validate secondary sorting by imaginary part.

Python-Numpy Code Editor:

Previous: Write a NumPy program to get the indices of the sorted elements of a given array.
Next: Write a NumPy program to partition a given array in a specified position and move all the smaller elements values to the left of the partition, and the remaining values to the right, in arbitrary order (based on random choice).

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.