3

Is it possible to sort a multidimensional array (row by row) using sort in C++ such that I can keep the index?

For example,

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

Becomes:

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

And the array with the index would be:

{2,0,1,3}
{0,3,2,1}
{1,3,0,2}
{ 1,0,2,3}
2
  • 1
    Are you really looking for a "yes" or "no" answer? Commented Jul 30, 2015 at 6:02
  • 2
    @RSahu, we can say OP, yes then lets go to hibernate ^_^ Commented Jul 30, 2015 at 6:10

2 Answers 2

2

First create the array of integer indices; here it is for 1D array:

int ind[arr.size()];
for( int i=0; i<arr.size(); ++i)
    ind[i] = i;

Then create the comparison object. Here is a ballpark of that in C++99 lingo; for C++11 you can shortcut that by using a lambda:

struct compare
{
    bool operator()( int left, int right ) {
        return arr[left] < arr[right];
    }
};

The sort the index array using that functor:

std::sort( ind, ind+sizeof(arr), compare );

Finally, use the sorted index array to order the values array.

Sign up to request clarification or add additional context in comments.

Comments

0

Yes. To sort row by row, you have to set the appropriate starting and ending point in the sort function.To keep the index part, you can first create pairs of the array elements and index using the make_pair command. After executing the above code, you can reconstruct the index array.

You will need to do something like this (I haven't tried it out though):

for (i = 0; i < matrix.size(); i++)
{
  sort(matrix[i].begin(), matrix[i].end());
}

Remember to add the index as the second element in the pair, because the default comparision operator for pairs checks the first element, followed by the second element.

2 Comments

Sorting that way works, but i dont have idea how to do the index part
@Eli: I have explained the index part also. Look at the make_pair command. So when you sort, the numbers will also have information about the index as they will be a pair. After that, using the .first and .second command, you can extract the values and indices.

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.