I'm trying to bubble sort the side diagonal of the matrix by decline, but the elements displayed are wrong. The problem is in indexes, but I do not know how to solve it
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <ctype.h>
int main () {
double a[100][100];
int n, m;
int i, j, b, c;
srand (time (NULL));
scanf ("%d", &n);
scanf ("%d", &m);
for ( i = 0; i < n; i )
{
for ( j = 0; j < m; j )
{
a[i][j] = 0.09 * (rand () 00) - 0.5;
}
}
printf ("Array A[N][M]: \n");
for ( i = 0; i < n; i )
{
printf ("\n");
for ( j = 0; j < m; j )
{
printf ("%6.0f", a[i][j]);
}
}
printf ("\n");
printf ("\nElements of the right diagonal are: \n");
for (j = 0; j < m; j )
{
printf( "%6.0lf", a[n - j - 1][j]);
}
printf ("\n");
printf ("\n Sorted array A[N][M]:");
for ( i = 0; i < n; i )
{
for ( j = 0; j < (m-1); j )
{
if (a[n - j - 1][j]<a[n-j][j 1])
{
int temp = a[n - j - 1][j];
a[n - j - 1][j] = a[n-j][j 1];
a[n-j-2][j 1] = temp;
}
}
}
printf ("\n");
for ( i = 0; i < n; i )
{
printf ("\n");
for ( j = 0; j < m; j )
{
printf ("%6.0f", a[i][j]);
}
}
printf ("\nElements of the right diagonal are: \n");
for (j = 0; j < m; j )
{
printf( "%6.0lf", a[n - j-2][j 1]);
}
return 0;
}
The goal is receiving a result of elements of diagonal sorted by a decline: (example)
0.74 4.35 7.05 9.1 6.46 6.6 7.48
5.41 7.28 4.85 2.8 4.28 7.47 7.87
5.83 2.73 9.42 7.14 1.38 7.22 1.21
6.91 3.8 9.51 4.56 8.74 7.43 5.63
9.65 8.04 1.02 9.71 6.02 5.61 1.15
2.35 1.04 2.23 4.43 6.45 4.5 4.31
2.7 5.79 3.33 8.44 6.99 4.79 1
Diagonal : 7.48 7.47 1.38 4.56 1.02 1.04 2.7
Sorted array:
0.74 4.35 7.05 9.1 6.46 6.6 7.48
5.41 7.28 4.85 2.8 4.28 7.47 7.87
5.83 2.73 9.42 7.14 4.56 7.22 1.21
6.91 3.8 9.51 2.7 8.74 7.43 5.63
9.65 8.04 1.38 9.71 6.02 5.61 1.15
2.35 1.04 2.23 4.43 6.45 4.5 4.31
1.02 5.79 3.33 8.44 6.99 4.79 1
Diagonal : 7.48 7.47 4.56 2.7 1.38 1.04 1.02
Hope for your help!
I managed to try the method given in this video: https://www.youtube.com/watch?v=YqzNgaFQEh8, but didn't succeed
CodePudding user response:
Code has at least these problems:
Not a swap
Mis-coded swap
int temp = a[n - j - 1][j];
a[n - j - 1][j] = a[n-j][j 1];
// a[n-j-2][j 1] = temp;
a[n-j][j 1] = temp;
Output format
If the goal is to see values to 2 decimal places, (and in columns of 7) use "%7.2g"
or "%7.2f"
, not "%6.0f"
.
Rather than print a '\n'
before a loop, I recommend afterwards.
// printf ("\n"); // Delete
for ( j = 0; j < m; j )
{
printf ("%6.0f", a[i][j]);
}
// Add
printf ("\n");