0

I have a matrix here and what I want is to copy its elements in a 2dim array or vector of vector(i prefer it) and sort them in a way that keep their indices. This is the matrix that I have:

For example for this matrix i want to keep these datas:(these datas contain indices and they are sorted)

1-5
1-2
2-4
4-5
2-5
1-4
3-5
1-3
3-4
2-3

Now which one do you suggest and how can I do it?

IMI
  • 105
  • 1
  • 1
  • 9
  • possible duplicate of [c++ sort keeping track of indices](http://stackoverflow.com/questions/10580982/c-sort-keeping-track-of-indices) – Cory Kramer Apr 08 '14 at 19:02
  • @Cyber what modifications should i apply in case of 2dim ? – IMI Apr 08 '14 at 19:11

2 Answers2

1
#include <vector> // for std::vector
#include <algorithm> // for std::sort

// your matrix
int matrix[5][5] = { ... };

// we use a struct to store entries with coordiantes
struct Entry {
    int row, col;
    int value;
};

// copy matrix data to vector    
std::vector<Entry> entries;
for(int i=0; i<5; i++) {
    for(int j=i+1; j<5; j++) {
        entries.push_back({i,j,matrix[i][j]});
    }
}

// sort vector
std::sort(entries.begin(), entries.end(),
    [](const Entry& a, const Entry& b) {
        return a.value> b.value;
    });
Danvil
  • 22,240
  • 19
  • 65
  • 88
0

I would say use a linked list. Create a NODE for every element such that each node has the following

node{    
int data;
int row;
int col;
node *next;
}

Put each of this node in an array so that you have array of nodes.

Once you have that you can sort the array using the data member of each node.

Since the row and col part of the node doesn't change you will be able to preserve the location of each element in the matrix using that.

sid
  • 95
  • 2
  • 11
  • @Quest can you explain a little more this answer i am little confused a sample code can clarify many things , THANKS – IMI Apr 08 '14 at 19:31
  • @IMI - Danvil has the implementation of what I was saying. Just look at the solution below. – sid Apr 08 '14 at 21:53