#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?