Hi
I need to write a code that will sort the absolute value of both an array that represents a vector, and an array that represents an nxn matrix. For the sorting of the vector-array I have written a program that works fine, but for the matrix I don't really know where to begin. It needs to be sorted in a way that if the 1. and 2. column of the vector-array switch place, the 1. and 2. column of the matrix-array should switch place as well. The following code I have written looks like this:
void SortNorm(double LamValsUs[NMAX], double WMatUs[NMAX][NMAX], double LamValsSo[NMAX], double VMatSo[NMAX][NMAX], int n, int r){
double temp;
int i,j;
for(i=1;i<n;i++){
for(j=0;j<(n+i);j++)
if(fabs(LamValsUs[j])<fabs(LamValsUs[j+1])){
temp=LamValsUs[j];
LamValsUs[j]=LamValsUs[j+1];
LamValsUs[j+1]=temp;
}
}
cout<<"The array is now sorted using Bubble-sort: ";
for(i=0;i<n;i++)
cout<<" "<<LamValsUs[i];
}
It needs to be sorted in a way that if the 1. and 2. column of the vector-array switch place, the 1. and 2. column of the matrix-array should switch place as well.
Please show an example input an what you want your program to output with that input.
1 2 3 4
int i,j;
for(i=1;i<n;i++){
for(j=0;j<(n+i);j++)
if(fabs(LamValsUs[j])<fabs(LamValsUs[j+1])){
It also looks like you have a possible out of bounds array access in the above code. Remember that arrays start at zero and end at size - 1. You appear to be trying to access your array at size + 3.
It may be easier to transpose the matrix from row major to column major order before your sort, then sort "lambdn" and when you swap the values of the "lamdbn" array swap the matrix column, then lastly transpose the array back into row major order.
You may also want to consider using vectors instead of arrays.