tags:

views:

1823

answers:

6

I'm looking for the best algorithm to take array A {0,1,2,3} and make order it like array B {3,1,0,2}. Any ideas?

+5  A: 

So if you have two arrays and they hold the same data just in different order then just do this:

A = B

I suspect that is not your situation so I think we need more info.

EBGreen
+1  A: 

In the example you gave (an array of numbers), there would be no point in re-ordering A, since you could just use B.

So, presumably these are arrays of objects which you want ordered by one of their properties.

Then, you will need a way to look up items in A based on the property in question (like a hashtable). Then you can iterate B (which is in the desired sequence), and operate on the corresponding element in A.

harpo
+1  A: 

Both array's contain the same values (or nearly so) but I need to force them to be in the same order. For example, in array A the value "3045" is in index position 4 and in array B it is in index position 1. I want to reorder B so that the index positions of like values are the same as A.

JC Grubbs
Please don't clarify your question with an answer, edit your original question to include the additional information. Because answers are sorted by vote, this means your clarification will always be at the bottom. It also means you're getting reputation for clarifying your answer, not good.
Mystere Man
+1  A: 

If they are nearly the same then here is some pseudo code:

Make an ArrayList
Copy the contents of the smaller array to the arraylist
for each item I in the larger array
    FInd I in the ArrayList
    Append I to a new array
    Remove I from the arraylist
EBGreen
+3  A: 

What you need to do is determine the ordering of B and then apply that ordering to A. One way to accomplish this is to undo the ordering of B and keep track of what happens along the way. Then you can do the reverse to A.

Here's some sketchy C# (sorry, I haven't actually run this)...

Take a copy of B:

List<int> B2 = new List<int>(B);

Now sort it, using a sort function that records the swaps:

List<KeyValuePair<int,int>> swaps = new List<KeyValuePair<int,int>>();
B2.Sort( delegate( int x, int y ) {
   if( x<y ) return -1;
   if( x==y ) return 0;
   // x and y must be transposed, so assume they will be:
   swaps.Add( new KeyValuePair<int,int>(x,y) );
   return 1;
});

Now apply the swaps, in reverse order, to A:

swaps.Reverse();
foreach( KeyValuePair<int,int> x in swaps )
{
   int t = A[x.key];
   A[x.key] = A[x.value];
   A[x.value] = t;
}

Depending how the built-in sort algorithm works, you might need to roll your own. Something nondestructive like a merge sort should give you the correct results.

Eric
+1  A: 

Could the issue be resolved using a Dictionary so the elements have a relationship that isn't predicated on sort order at all?

Jeremy