add matrix_sort

This commit is contained in:
juan 2021-12-02 21:49:33 +08:00
parent 32e25c1be0
commit 640706968c
No known key found for this signature in database
GPG key ID: 5C1E5093C74F1DC7

67
pset11/2-5-MatrixSort.c Normal file
View file

@ -0,0 +1,67 @@
#include <stdio.h>
#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;
}