我试着用冒泡排序法按下降方向交换侧对角线的元素,问题是显示的元素是错误的,所以交换不起作用
#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
我不知道为什么它不工作,所以我希望你的帮助!
1条答案
按热度按时间qco9c6ql1#
时间复杂度O(n):您需要两个嵌套的
for
循环: