# Sorting 2D Array C++

### Tags:

#### sorting

Is it possible to sort a 2D Array using qsort or std::sort in C++ such that the elements are in increasing order when read from left to right in each row or from top to bottom in each column?

For example,

13, 14, 15, 16
1, 4, 3, 2
7, 5, 7, 6
9, 10, 11, 12

Becomes:

{ 1, 2, 3, 4 }
{ 5, 6, 7, 8 }
{ 9, 10, 11, 12 }
{ 13, 14, 15, 16 }

I know you can do it by creating two comparison functions and then first sorting each row then comparing the first elements of each row to establish the columns, but is there a way to do it in one function itself?

618

#### 1110101001

# include <iostream>
using namespace std ;

void swap (int &x , int &y)
{
int temp = x ;
x = y ;
y = temp ;
}

void main ()
{
int arr [3][3] = {{90,80,70},{60,50,40},{30,100,10}} ;
int x ;

for (int k = 0; k < 3; k++)
{
for (int m = 0; m < 3; m++)
{
x = m+1;
for (int i = k; i < 3 ; i++)
{
for (int j = x; j < 3; j++)
{
if (arr [k][m] > arr [i][j])
swap(arr [k][m] ,arr [i][j]);
}
x=0;
}
}
}

for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << arr [i][j] << " ";
}
}

system("pause");
}

C++ Sorting 2-D array ascendingly

187

#### Eslam

Yes. C++ STL library is built with separation of algorithms and containers. What links them together is iterators. Raw pointer is iterator, therefore it is possible to initialize vector with raw pointers and then sort that vector as usual.

std::vector<int> v(arr2d, arr2d + N); // create a vector based on pointers
// This assumes array is contiguous range
// in memory, N=number of elemnts in arr2d
// using default comparison (operator <):
std::sort (v.begin(), v.end());

// cout by 4 elements in a row
26