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,855 questions

51,776 answers

573 users

How to sort each row from a two-dimensional array in C++

1 Answer

0 votes
#include <iostream>
#include <algorithm> // For std::sort
 
#define ROWS 3
#define COLS 4
 
// Function to sort each row of a 2D array
void sortRows(int arr2D[ROWS][COLS], int rows, int cols) {
    for (int i = 0; i < rows; ++i) {
        std::sort(arr2D[i], arr2D[i] + cols);
    }
}
 
void print2DArray(const int arr2D[ROWS][COLS], int rows, int cols) {
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            std::cout << arr2D[i][j] << " ";
        }
        std::cout << std::endl;
    }
}
 
int main() {
    int arr2D[ROWS][COLS] = {
        {4, 2, 1, 3},
        {8, 6, 5, 7},
        {12, 10, 11, 9}
    };
 
    sortRows(arr2D, ROWS, COLS);
 
    print2DArray(arr2D, ROWS, COLS);
 
    return 0;
}
 
  
  
/*
run:
 
1 2 3 4 
5 6 7 8 
9 10 11 12 
  
*/

 



answered Mar 16, 2025 by avibootz
edited Mar 16, 2025 by avibootz
...