sorting corresponding arrays

Say I have two integer arrays, {a1,a2,...,an} and {b1,b2,...,bn}. Can I sort the first array (in increasing order) and then move the members of the second array to the position which the member of the first array in the corresponding position has been moved to?
For sure you can do this.
How can I do it?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <iterator>
#include <algorithm>

void bubblesort(int v[], int w[], int n) {
    for (int i = n - 1; i > 0; i--) {
        for (int j = 0; j < i; j++) {
            if (v[j] > v[j + 1]) {
                int vswp = v[j];
                int wswp = w[j];
                v[j] = v[j + 1];
                v[j + 1] = vswp;
                w[j] = w[j + 1];
                w[j + 1] = wswp;
            }
        }
    }
}

int main()
{
    using namespace std;
    int a[] = { 5, 2, 3, 1, 5, 3, 4 };
    int b[] = { 1, 2, 3, 4, 5, 6, 7 };
    
    bubblesort(a, b, 7);
    copy(a, a+7, ostream_iterator<int>(cout, " "));
    cout << endl;
    copy(b, b+7, ostream_iterator<int>(cout, " "));
    cout << endl;
}
1 2 3 3 4 5 5
4 2 3 6 7 1 5
Thanks, I see. I should have been able to come up with that!
I came up with a better way to do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <boost/foreach.hpp>
#include <iostream>
#include <map>
#define foreach BOOST_FOREACH

int main()
{
    using namespace std;
    typedef multimap<int,int> int_map;

    int a[] = { 5, 2, 3, 1, 5, 3, 4 };
    int b[] = { 1, 2, 3, 4, 5, 6, 7 };

    int_map arrays;
    foreach (int i, b)
        arrays.insert(make_pair(a[i - 1], b[i - 1]));

    foreach (int_map::value_type p, arrays)
        cout << p.first << " ";
    cout << endl;

    foreach (int_map::value_type p, arrays)
        cout << p.second << " ";
    cout << endl;
}
Last edited on
Topic archived. No new replies allowed.