Impact-Site-Verification: dbe48ff9-4514-40fe-8cc0-70131430799e

Search This Blog

Sort a list of complex numbers based on how far they are from the origin


Given a list of complex numbers z, return a list zSorted such that the numbers that are farthest from the origin (0+0i) appear first.
So if z is
 z = [-4 6 3+4i 1+i 0]
then the output zSorted would be
 zSorted = [6 3+4i -4 1+i 0]


Algorithm:

Step 1:
Take absolute part

Step 2:
Sort them in descending order

Step 3:
Now from absolute value go back to complex number.

Code:

clc
z=input('Enter the array');
Y=abs(z);
Y=fliplr(sort(Y));
A=[];
for i=1:length(Y)
    m=Y(i);
    for i=1:length(z)
        if(m==abs(z(i)))
            A=[A z(i)];
        end
    end
end
disp(A);

Output:


Explanation:


 Reference Video:





No comments

Popular Posts

Followers