Sorting of arrays

May 27, 2017 at 8:52am
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];
}
May 27, 2017 at 12:55pm
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.

Please use code tags when posting code.
May 27, 2017 at 1:22pm
An example for the input:
lambd= [2 4 -3 1]
W=
1 1 1 0
1 -1 0 1
1 1 -1 0
1 -1 0 -1

Where the corresponding output should look like this:
lambdn=[4 -3 2 1]
V=
1 1 1 0
-1 0 1 1
1 -1 1 0
-1 0 1 -1

Thank you
Last edited on May 27, 2017 at 1:24pm
May 27, 2017 at 5:49pm
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.


May 27, 2017 at 9:30pm
Standard Bubble Sort Function, May be helpfull

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void bubble_sort(long list[], long n)
{
  long c, d, t;
 
  for (c = 0 ; c < ( n - 1 ); c++)
  {
    for (d = 0 ; d < n - c - 1; d++)
    {
      if (list[d] > list[d+1])
      {
        /* Swapping */
 
        t         = list[d];
        list[d]   = list[d+1];
        list[d+1] = t;
      }
    }
  }
}


Consider the Array index bound.

this page explanation may help you.

https://www.tutorialspoint.com/data_structures_algorithms/bubble_sort_program_in_c.htm
Last edited on May 28, 2017 at 5:03pm
May 28, 2017 at 9:19pm
Thank you very much for the answers, I will try to sort it out.
Topic archived. No new replies allowed.