4

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?

7
  • 1
    If it is an NxN matrix, then copy the elements to a vector. Sort the vector and then copy each row back to array from vector. Commented Oct 8, 2013 at 1:11
  • Doesn't that only sort the rows though? What about the columns? Commented Oct 8, 2013 at 1:16
  • Copy it to a vector, sort it as a 1D array (which it is now), and then copy it back to the 2D array. Commented Oct 8, 2013 at 1:17
  • hmmm ... If the entire vector is sorted, then copying it back to array will sort the columns as well. For example, if 4 is at NxN position then it would come to 1*N element after sorting and copying to array ( Here N = 4). Commented Oct 8, 2013 at 1:19
  • 1
    You can try to rely on the fact that a 2D array is merely special syntax and it's arranged in memory sequentially. Try something like: std::sort(&array2d[0][0], &array2d[0][0] + N*M, std::less<int>()); Commented Oct 8, 2013 at 1:24

5 Answers 5

3

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
Sign up to request clarification or add additional context in comments.

Comments

3
# 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

1 Comment

The asker requested an answer "using qsort or std::sort"
1

In theory you should be able to input the 16 numbers into an array. Use a for loop, maybe even a nested one, to sort the numbers. Then as for output you want the ascending numbers in four groups of four?

cout<<Vector[0]<<Vector[1]<<Vector[2]<<Vector[3]<<endl;
cout<<Vector[4]<<Vector[5]<<Vector[6]<<Vector[7]<<endl;
cout<<Vector[8]<<Vector[9]<<Vector[10]<<Vector[11]<<endl;
cout<<Vector[12]<<Vector[13]<<Vector[14]<<Vector[15]<<endl;

very arbitrary but I'm not quite sure of the question.

Comments

1

First Make a 2D vector .

Sort each vector in this 2D vector

Sort the whole vector

Code :

#include <iostream>
#include <vector>
#include <algorithm>

template <class T>
void Sort2dArray(std::vector<std::vector<T>> & numbers)
{

    for(auto & i : numbers){//sort each vector<T> in numbers
        std::sort(i.begin(),i.end());
    }
    std::sort(numbers.begin(),numbers.end(),[](//sort numbers by defining custom compare 
              const std::vector<T>& a,const std::vector<T>&b){
        for(int i=0;i<a.size()&&i<b.size();i++)
        {
            if(a[i]>b[i])
                return false;
            else if(a[i]<b[i])
                return true;
        }
        return a.size()<b.size() ? true : false;
    });
}

int main()
{
    std::vector<std::vector<int>> numbers={ {13, 14, 15, 16},
                                            {1, 4, 3, 2},
                                            {8, 5, 7, 6},
                                            {9, 10, 12,11}};
    Sort2dArray(numbers);//sort array

    //write sorted array
    for(auto i:numbers)
    {
        for(auto j:i)
            std::cout<<j<<" ";
        std::cout<<"\n";
    }
}

Comments

-1

**Sorting 2D array in c++**

#include <iostream>

using namespace std;

int main()
{
    int i,j,k,m,temp,n,limit;
    int** p;


    cout<<"Enter the limit:";
    cin>>limit;

    p=new int*[limit];

//inputing
    for(i=0;i<limit;i++)
    {
        p[i] = new int[limit];

        for(j=0;j<limit;j++)
        {
          cin>>p[i][j];
        }

    }

//sorting
    for(i=0;i<limit;i++)
    {
        for(j=0;j<limit;j++)
        {
            if (j==limit-1 && i<limit-1)
            {
                n =-1;
                m=i+1;
            }
            else
            {
                m=i;
                n=j;
            }

            for(k=n+1;k<limit;k++)
            {
                if(p[i][j] > p[m][k] )
                {
                    temp = p[i][j];
                    p[i][j] = p[m][k];
                    p[m][k] = temp;
                }

                if(k==limit-1 && m<limit-1) { m++;  k=-1;  }

            }
        }
    }

    //displaying
    for(i=0;i<limit;i++)
    {
        for(j=0;j<limit;j++)
        {
            cout<<p[i][j]<<endl;
        }

    }

    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.