0
#include <stdio.h>

int main() {
    int a;
    printf("Enter the number of rows: ");
    scanf("%d", &a);
    int b;
    printf("Enter the number of columns: ");
    scanf("%d", &b);
    int x[a][b];

    for (int i = 0; i < a; i++) {
        for (int j = 0; j < b; j++) {
            printf("Enter element at row %d column %d: ", i + 1, j + 1);
            scanf("%d", &x[i][j]);
        }
    }

    for (int i = 0; i < a * b; i++) {
        for (int j = 0; j < a; j++) {
            for (int k = 0; k < b; k++) {
                int crow = j;
                int ccol = k;
                int nrow = j;
                int ncol = k + 1;
                if (ncol == b) {
                    nrow = j + 1;
                    ncol = 0;
                }
                if (crow > nrow) {
                    if (x[crow][ccol] > x[nrow][ncol]) {
                        int temp = x[crow][ccol];
                        x[crow][ccol] = x[nrow][ncol];
                        x[nrow][ncol] = temp;
                    }
                }
            }
        }
    }

    printf("Sorted matrix:\n");
    for (int i = 0; i < a; i++) {
        for (int j = 0; j < b; j++) {
            printf("%d ", x[i][j]);
        }
        printf("\n");
    }

    return 0;
}

I'm trying to sort a 2D matrix using the Bubble Sort algorithm in C. The program compiles and runs without errors, but it's not producing the expected sorted result. Instead, it appears to print the original matrix as-is.

I've double-checked my code, but I can't seem to find the issue. Can someone please review my code and help me understand what's going wrong with the sorting algorithm?

1 Answer 1

0

I believe your if statement is in correct:

if (crow > nrow)

as crow can never be greater than nrow per definition. crow = j and nrow = j or nrow = j + 1 so crow <= nrow in all cases. As such your if statements are never checked.

Besides that you are missing the edge case when k == b - 1 and j == b - 1 aka your last row and column. In this case nrow will loop to the next row which does not exist.

Hope this helped you get further!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.