Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,922 questions

51,855 answers

573 users

How to sort only the second row of a matrix in C

1 Answer

0 votes
#include <stdio.h>  
#include <stdlib.h> 
 
#define COLS 5
 
int compare(const void* a, const void* b) {
    return (*(int*)a - *(int*)b);
}

void print_matrix(int matrix[][COLS], int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%2d", matrix[i][j]);
        }
        printf("\n");
    }
}
 
int main()
{
    int matrix[][COLS] = {
                    {3, 2, 5, 1, 4},
                    {4, 9, 7, 1, 5},
                    {9, 3, 2, 0, 1},
                    {6, 8, 3, 7, 0}
    };
 
    int rows = (sizeof(matrix) / sizeof(matrix[0]));
    int cols = (sizeof(matrix) / sizeof(matrix[0][0])) / rows;
 
    qsort(matrix[1], cols, sizeof(int), compare);
 
    print_matrix(matrix, rows, cols);
 
    return 0;
}
 
 
 
 
 
/*
 
run:
 
 3 2 5 1 4
 1 4 5 7 9
 9 3 2 0 1
 6 8 3 7 0
 
*/

 



answered Mar 15, 2024 by avibootz

Related questions

1 answer 76 views
1 answer 82 views
1 answer 96 views
1 answer 89 views
2 answers 141 views
1 answer 90 views
...