diff --git a/pset11/2-5-MatrixSort.c b/pset11/2-5-MatrixSort.c new file mode 100644 index 0000000..b493e2d --- /dev/null +++ b/pset11/2-5-MatrixSort.c @@ -0,0 +1,67 @@ +#include +#pragma gcc optimize("Ofast, inline") + +int getSum(int *arr, int len); +// Use bubble sort +void swapArray(int *l, int *r, int len); +void swap(int *l, int *r); + +int main(void) { + // Initialize arrays + int n; + scanf("%d", &n); + int matrix[n][n]; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + scanf("%d", &matrix[i][j]); + } + } + + // Storing the average value + int sum[n]; + for (int i = 0; i < n; i++) { + sum[i] = getSum(matrix[i], n); + } + + // Bubble sorting the average value + for (int i = 0; i < n; i++) { + for (int j = 0; j < n - 1; j++) { + if (sum[j] > sum[j + 1]) { + /* printf("sum: %d %d\n", sum[j], sum[j + 1]); */ + swap(&sum[j], &sum[j + 1]); + swapArray(matrix[j], matrix[j + 1], n); + } + } + } + + // Print the result + for (int i = 0; i < n; i++) { + for (int j = 0; j < n - 1; j++) { + printf("%d ", matrix[i][j]); + } + printf("%d\n", matrix[i][n - 1]); + } + + return 0; +} + +int getSum(int *arr, int len) { + int sum = 0; + for (int i = 0; i < len; i++) { + sum += arr[i]; + } + return sum; +} + +void swap(int *l, int *r) { + int tmp = *l; + *l = *r; + *r = tmp; +} + +void swapArray(int *l, int *r, int len) { + for (int i = 0; i < len; i++) { + swap(&l[i], &r[i]); + } + return; +}