Third smallest number in matrices and its addition
How can i addition one + one matri开发者_高级运维c (array data structure) and after it find the third smallest number in it in C language (not C++)? Thank you for the code.
Example code follows:
void addMatrix(unsigned int size, double const * const a, double const * const b, double * const res) {
int i;
for (i = 0; i < size * size; ++i)
res[i] = a[i] + b[i];
}
double findThirdSmallest(unsigned int size, double const * const input) {
//save the three smallest values inside res
double res[3];
int i;
for (i = 0; i < 3; ++i) {
res[i] = LDBL_MAX;
}
for (i = 0; i < size * size; ++i) {
int j;
for (j = 0; j < 3; ++j) {
if (input[i] < res[j]) {
int k;
for (k = 2; k != j; --k) {
res[k] = res[k - 1];
}
res[j] = input[i];
break;
}
}
}
return res[2];
}
EDIT: Changing the type and the size of the matrix will be your work.
- First decide how to represent the matrix (hint: use an array of arrays)
- Then figure out how to add two matrices - this is simple
- Then, how do you find the 3rd smallest element in a sequence? There are many ways! Is efficiency especially important for you? What algorithmic complexity is required?
If you are trying to access SIMD instructions, I don't believe there is an approach that will do both at the same time. If you are not trying to do use SIMD, then just keep a temp array of the three smallest values (like a priority queue) that is updated each time a sum is computed in the matrix.
If this were C++, the priority queue could be kept in a functor object used by the STL algorithms.
精彩评论