I'm trying to use a bubble sort method to swap the elements of the side diagonal by the decline. The problem is the elements displayed are wrong, so that swapped doesn't work
#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;
int flag;
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]);
}
flag = 0;
for (i = 0; i <= (n-1); i )
{
if (a[i][j]<a[i][i-1])
{
int temp = a[i][j];
a[i][n-i-1]=a[i 1][n-i];
a[i 1][n-i] = temp;
flag = 1;
}
if (flag == 0)
{
break;
}
}
printf ("\n");
printf ("\nElements of the sorted right diagonal are: \n");
for (i = 0; i <= (n-1); i )
{
printf( "%6.0lf", a[i 1][n-i]);
}
return 0;
}
The goal is to receive a result of sorted elements of side diagonal by decline: (example)
Array A[N][M]:
86 81 60 38
86 40 84 17
56 23 45 19
13 16 43 86
Elements of the side diagonal are:
13 23 84 38
Elements of the sorted side diagonal are:
84 38 23 13
I don't know why it is not working, so I hope for your help!
CodePudding user response:
Bubble sort runs in O(n²): You need two nested for
loops:
bool bubble_sort_diag(const size_t nrows, const size_t ncols, double array[nrows][ncols])
{
size_t dim = nrows < ncols ? nrows : ncols; // In case the matrix is not square
bool swapped = false;
for (size_t i = 0; i < dim - 1; i) {
swapped = false;
for (size_t j = 0; j < dim - i - 1; j) {
if (array[j][dim-j-1] > array[j 1][dim-j-2]) {
swap_double(&array[j][dim-j-1], &array[j 1][dim-j-2]);
swapped = true;
}
}
if (!swapped)
return true; // Sorting performed: Array was initially unsorted.
}
return false; // Sorting was not performed: Array was initially sorted.
}