Hi, i have to sort two arrays in a specific way.

I have two parallel arrays A[N] and B[N].
Ι have to sort A in descending order. The changes in A should be happened in B at the same time.

If 2 or more items in A is the same, they should be sorted in ascending order with respect to B.

Can I do that sort with STL?

Example:
Start:
A B
1 4
3 8
3 2
End:
A B
3 2
3 8
1 4

I think since the other array must track the indicies of the first it would be difficult to use the STL methods anyway. What are some of the things you have tried?

I have made it with bubble sort

So do your bubble sort and allow the other array to follow along (when you're update index numbers for A array in your sort, update B with the same changes.

Then comb along A (with a loop) and find the first set of duplicates (check index n versus index n+1, and n versus n+2 if there's a match).

Over those index numbers do a mini bubble sort of the B array (since the A values are all the same leave them in place and just sort the select B values). Move on to your next set of duplicates, etc.

Can I do that sort with STL?

Do you need to have parallel arrays, or can you put them in a container of some sort?

``````#include <iostream>
#include <algorithm>

struct T
{
int a,b;
};

void display(const T *data, size_t size)
{
std::cout << "A B\n";
for ( size_t i = 0; i < size; ++i )
{
std::cout << data[i].a << " " << data[i].b << "\n";
}
}

int compare(const T &x, const T &y)
{
if ( x.a > y.a )
{
return 1;
}
if ( x.a < y.a )
{
return -1;
}
if ( x.b < y.b )
{
return 1;
}
if ( x.b > y.b )
{
return -1;
}
return 0;
}

int main()
{
T array[] = {{1,4},{3,8},{3,2}};
std::cout << "Before:\n";
display(array, sizeof array / sizeof *array);
std::sort(array, array + sizeof array / sizeof *array, compare);
std::cout << "After:\n";
display(array, sizeof array / sizeof *array);
}

/* my output
Before:
A B
1 4
3 8
3 2
After:
A B
3 2
3 8
1 4
*/``````

Thank you Dave Sinkula.