Sorting Complex Number in C++

Hello,

I wrote a program for sorting complex numbers with C++.
To print the sign of the imaginary part of the number I wrote the below function. Is it true?


Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
 #include <iostream>
using namespace std;
struct Complex
{
	double real;
	double img;
};
void swap(Complex* xp, Complex* yp)
{
	Complex temp = *xp;
	*xp = *yp;
	*yp = temp;
}
int main()
{
	int n;
	cout << "Number?:";
	cin >> n;

	Complex* myArray = new Complex[n];
	for (size_t i = 0; i < n; i++)
	{
		cout << "Real: ";
		cin >> myArray[i].real;
		cout << "Imaginary: ";
		cin >> myArray[i].img;
	}

	for (int i = 0; i < n - 1; i++)
	{
		for (int j = 0; j < n - i - 1; j++)
		{
			if (myArray[j].real > myArray[j + 1].real)
			{
				swap(&myArray[j], &myArray[j + 1]);
			}
			else if (myArray[j].real == myArray[j + 1].real)
			{
				if (myArray[j].img > myArray[j + 1].img)
				{
					swap(&myArray[j], &myArray[j + 1]);
				}
			}
		}
	}
	cout << endl;
	for (size_t i = 0; i < n; i++)
	{
		cout << myArray[i].real;
		if (myArray[i].img < 0)
		{
			cout << myArray[i].img<<"i";
		}
		else
		{
			cout <<"+"<< myArray[i].img << "i";
		}
		cout << endl;
	}
}
Last edited on
You can't meaningfully sort complex numbers.
Thank you, could you please more explain?
It would make more sense to sort them by their absolute value (distance from the origin).
https://en.cppreference.com/w/cpp/numeric/complex/abs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <vector>
#include <complex>
#include <algorithm>

int main()
{
    std::vector<std::complex<double>> v;
    std::complex<double> z;
    while (std::cin >> z) // enter numbers as (1, 2)
        v.push_back(z);
    std::sort(v.begin(), v.end(),
        [](auto&a, auto&b){return std::abs(a) < std::abs(b);});
    for (auto x: v)
        std::cout << x << '\n';
}

Shervan360 wrote:
Thank you, could you please more explain?

At the moment, you are sorting by real part, or imaginary part if real parts are equal. But this will end up with massive discontinuities in the order relation.


Secondly, comparing two doubles for equality - within the finite accuracy of floating-point arithmetic - is asking for trouble.


Thirdly, think of the disastrous consequences. According to your scheme (with i the square root of -1):
-1 < i
OK, but then square it:
1 < -1
See the problem?
Last edited on
Topic archived. No new replies allowed.