带有标志的气泡排序无法正常工作



我试图使用冒泡排序方法通过下降来交换侧对角线的元素。问题是显示的元素是错误的,所以交换不起作用

#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 () %1000) - 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;
}

的目标是得到对角线边的元素按递减排序的结果:(例子)

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 

我不知道为什么它不工作,所以我希望你的帮助!

冒泡排序运行时间为O(n²):您需要两个嵌套的for循环:

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.
}

最新更新