In C++: #include <math.h> typedef struct { double re, im; } complex; #define com
ID: 3590772 • Letter: I
Question
In C++:
#include <math.h>
typedef struct { double re, im; } complex;
#define compmag(a) sqrt((a.re*a.re)+(a.im*a.im))
The first line instructs the compiler to use some additional math functions; we are interested in square root. The second line creates a custom datatype which is a structure containing 2 real numbers (this is from the lectures); this is also a global definition since it is not within any functions. The last line is a quick macro which determines the magnitude of a complex number; we will need this in our modified sorting routine. Copy your existing sorting function which operates on an array of doubles into a new function called “mycomplexsort”. Change the datatypes of your list argument to “complex” as well as your temporary variable for swapping. You need to also change your comparison line so that it properly compares complex numbers. Use the macro above to perform the magnitude calculation. Write ONLY that line below:
int mycomplexsort(int entries, double *list2) {
int n = 0;
int j, maxindex, i;
double temp;
/* add your local variables here */
for (j = 0; j < entries - 1; j++) {
temp = list2[j];
maxindex = j;
for (i = j + 1; i < entries; i++, n++) {
if (list2[i] <= temp) {
temp = list2[i];
maxindex = i;
}
}
if (maxindex != j) {
temp = list2[maxindex];
list2[maxindex] = list2[j];
list2[j] = temp;
}
}
/* add your sorting code here */
return n;
}
Explanation / Answer
#include <iostream>
#include <math.h>
typedef struct { double re, im; } complex;
#define compmag(a) sqrt((a.re*a.re)+(a.im*a.im))
int mycomplexsort(int entries, complex *list2) {
int n = 0;
int j, maxindex, i;
double temp;
complex temp_complex;
/* add your local variables here */
for (j = 0; j < entries - 1; j++) {
temp = compmag(list2[j]);
maxindex = j;
for (i = j + 1; i < entries; i++, n++) {
if (compmag(list2[i]) <= temp) {
temp = compmag(list2[i]);
maxindex = i;
}
}
if (maxindex != j) {
temp_complex = list2[maxindex];
list2[maxindex] = list2[j];
list2[j] = temp_complex;
}
}
/* add your sorting code here */
return n;
}
int main(){
complex comp[] = {{4,5},{3,4}};
int length = sizeof(comp)/sizeof(complex);
//Before sorting
std::cout << "Before Sorting : " << std::endl;
for (int i=0; i<length; i++){
std::cout << comp[i].re << " " << comp[i].im << std::endl;
}
//After sorting
std::cout << "After Sorting : " << std::endl;
int res = mycomplexsort(2,comp);
for (int i=0; i<length; i++){
std::cout << comp[i].re << " " << comp[i].im << std::endl;
}
}