Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have an array of length n that contains numbers from 0 to n-1 in random order. I now want to "inverse" this array to one that where index i corresponds to the location of i in the source array.


Source_Array = {2,0,1}

Transform to:

Result_Array = {1,2,0}

This means I find the index 0 at position 1 in my source, 1 is at location 2 and so on.

I did this with the following function:

Dim Sourcelist As List(Of Integer) = Source.ToList
Dim Result(Source.Count - 1) As Integer
For i = 0 To Source.Count - 1
   Result(i) = Sourcelist.IndexOf(i)

Casting the array to List and then slowly using IndexOf to select the indices is not really great. Is there a better method maybe using LINQ?

Both VB.NET and C# answers are very much appreciated.

share|improve this question
up vote 6 down vote accepted

Unfortunately I don't really know visual basic but I think that you will find it easy to grasp the idea (and implement it in any language) of the following java code:

int[] source = new int[]{2,0,1};
int[] dest = new int[source.length];
for (int i = 0; i < source.length; i += 1) {
    dest[source[i]] = i;

The code runs at \$O(n)\$ time whereas if you search for every element you get \$O(n^2)\$ time.

share|improve this answer
Perfect, that's an elegant solution to this problem. – Jens Apr 8 '14 at 15:32

I'm not very good with LINQ but here's my take at it.

Dim Result_Array = From v In Source_Array Select Source_Array(v)
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.