C语言 带标志的冒泡排序无法正常工作

enyaitl3  于 2022-12-17  发布在  其他
关注(0)|答案(1)|浏览(132)

我试着用冒泡排序法按下降方向交换侧对角线的元素,问题是显示的元素是错误的,所以交换不起作用

#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

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

qco9c6ql

qco9c6ql1#

时间复杂度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.
}

相关问题