hi.can someone help me to sort a two dimensional array.. below is how i sort a single dimensional array, i want it in a similar way... im just not good at managing the for loop...

single array :            

#include <iostream>
using namespace std;

int main ()
{
    int M[5] = { 17, 23, 7, -3, 18};
    int i,j;
    int temp;

    for (j=4; j>0; j--)

        for (i=0; i<j;i++)
        {
            if (M[i] > M[i+1])
            {
                temp = M[i+1];
                M[i+1]= M[i];
                M[i] = temp;
            }
        }
        cout << "Sorted List : ";
        for (i=0;i<=4;i++)
            cout << M[i] << " " ;   
        return 0
}

`

`

Recommended Answers

All 2 Replies

You could go about this using vectors and the sort stl algorithm if your aim is to just sort a 2d array (provided you dont have to write your own sort routine).

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

#define all(c) sort(c.begin(), c.end())

using namespace std;

int main()
{
   vector< vector<int> > my_vect(3,vector<int>(4));

   for (int i = 0; i < 3; i++)
       for (int j = 0; j < 4; j++)
           my_vect[i][j] = 4 + i - j;

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

   for (int i = 0; i < 3; i++)
   {
       all(my_vect[i]);
   }
   cout << endl;


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

  return 0;


}

Here's a way that uses a loop you're familiar with and sorts the 2D array in a linear fashion, which I assume is what you want:

void sort(int myArray[5][3],  int rows, int col)
{
    for(int i = rows; i >=0; i--)
    {

        for (int j = 0; j < i; j++)
        {
            if (myArray[(int)(j / col)][j % col] > myArray[(int)((j + 1) / col)][(j + 1) % col])
            {
                int temp = myArray[(int)(j / col)][j % col];
                myArray[(int)(j / col)][j % col] = myArray[(int)((j + 1) / col)][(j + 1) % col];
                myArray[(int)((j + 1) / col)][(j + 1) % col] = temp;
            }
        }
    }
}

The limit of the loop is the total number of elements - 1, as if it was a 1D array with that many elements. Then in your j loop, (int)(j/col) returns the index of the first dimension([5]), and j%col returns the index of the second dimension([3]).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.