How to sort the boundary elements of a matrix in C

1 Answer

0 votes
#include <stdio.h>  
#include <stdlib.h>  

#define COLS 5

int GetBoundariesLength(int matrix[][COLS], int rows, int cols) {
    return (rows * 2) + (cols * 2) - 4;
}

int compare(const void* a, const void* b) {
    return (*(int*)a - *(int*)b);
}

void SortMatrixBoundaries(int matrix[][COLS], int rows, int cols) {
    int arr_size = GetBoundariesLength(matrix, rows, cols);
    int* p = (int *)malloc(arr_size * sizeof(int));

    int index_arr = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (i == 0 || j == 0 || i == rows - 1 || j == cols - 1) {
                p[index_arr++] = matrix[i][j];
            }
        }
    }

    qsort(p, arr_size, sizeof(int), compare);

    index_arr = 0;

    for (int j = 0; j < cols; j++) {
        matrix[0][j] = p[index_arr++];
    }

    for (int j = 0; j < cols; j++) {
        if (j == cols - 1) {
            for (int i = 1; i < rows; i++) {
                matrix[i][j] = p[index_arr++];
            }
        }
    }

    for (int j = cols - 2; j > -1; j--) {
        matrix[rows - 1][j] = p[index_arr++];
    }

    for (int i = rows - 2; i > 0; i--) {
        matrix[i][0] = p[index_arr++];
    }
    
    free(p);
}


void PrintMatrix(int matrix[][COLS], int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%3d", matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int matrix[][COLS] = { { 1,  2,  3,  4,  5},
                           { 6,  7,  8,  9, 10},
                           {11, 12, 13, 14, 15},
                           {16, 17, 18, 19, 20} };

    int rows = sizeof matrix / sizeof matrix[0];
    int cols = sizeof matrix[0] / sizeof(int);

    SortMatrixBoundaries(matrix, rows, cols);

    PrintMatrix(matrix, rows, cols);

    return 0;
}




/*
run:

  1  2  3  4  5
 20  7  8  9  6
 19 12 13 14 10
 18 17 16 15 11

*/

 



answered Jun 29, 2023 by avibootz
edited Jun 30, 2023 by avibootz

Related questions

1 answer 72 views
1 answer 75 views
1 answer 74 views
2 answers 89 views
1 answer 71 views
1 answer 75 views
2 answers 82 views
...