4

Suppose we have three arrays a, b, and c:

int a[1000] = {3,1,5,4};
int b[1000] = {7,9,11,3};
char c[1000] = {'A','B','C','D'};

Array a is then sorted, so it becomes:

a == {1,3,4,5}

Is it possible to arrange for the other two arrays to have their elements rearranged by index, so that they mirror the placement of the sorted elements in the sorted array a? In this example, this should result in

b == {9,7,3,11}
c == {'B','A','D','C'}

How can I achieve this?

2
  • Why x[1000] when just using 4 elements? Commented Sep 7, 2011 at 7:10
  • Not related, but you need to enclose your chars in 's: char c[1000] = {'A', 'B', 'C', 'D'} (unless they are char variables defined elsewhere) Commented Sep 7, 2011 at 7:11

2 Answers 2

3

you can create a class ABC, which will hold 3 fields: int a, int b, char c.
implement the operator< for this class, and create a ABC[] of the approppriate size and populate it such that ABC[i] = ABC(a[i],b[i],c[i]).

implement the operator< so it will compare only a, and use sort on the ABC array.

after done sorting, you have all your elements in the desired order, just iterate the ABC array and populate the other arrays.

EDIT:

simplified [and hard coded] code sample:

#include <iostream>
#include <algorithm>
using namespace std;

class ABC { 
public: 
  int a,b;
  char c;
  bool operator<(const ABC& other) const { 
    return a < other.a;
  }
};
int main() { 
  int a[4] = {3,1,5,4};
  int b[4] = {7,9,11,3};
  char c[4] = {'A','B','C','D'};
  ABC abc[4];
  for (int i = 0; i< 4; i++) { 
    abc[i].a = a[i];
    abc[i].b = b[i];
    abc[i].c = c[i];
  }
  sort(abc,abc+4);
  for (int i = 0; i < 4; i++) { 
    a[i] = abc[i].a;
    b[i] = abc[i].b;
    c[i] = abc[i].c;
  }
  cout << "a= [" << a[0] << ", " << a[1] << ", " << a[2] << ", " << a[3] << "]" << endl;
  cout << "b= [" << b[0] << ", " << b[1] << ", " << b[2] << ", " << b[3] << "]" << endl;
  cout << "c= [" << c[0] << ", " << c[1] << ", " << c[2] << ", " << c[3] << "]" << endl;
  return 0;
}

works good for me on codepad: http://codepad.org/eCyNkyqR

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

1 Comment

can you show me code example, cause i am new so don't really understand that
0

It's not exactly what you need, but you can achieve similar results by using std::map and std::sort:

std::map<int, std::pair<int, char> > someArray;

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.