panos_vs_panos
panos_vs_panos

Reputation: 1

Transform an array from index to value sorting

I have an int[] values which has every time diffenent size of numbers. It's form is something like that:

Index: 1 2 3 4 5
Value: 3 5 1 2 4 

I want to tranform this array and return a new int[] which is sorted by value:

Index: 3 4 1 5 2
Value: 1 2 3 4 5 

In other words i want to change the sorting and return a new int[] sorted by value, not by index. How can i do that ?

An one-d array which indicates the index sorted by value can do the work, for example if the int [] values is something like that 400 500 232 123 999 the new int [] will be 3 2 0 1 4

Upvotes: 0

Views: 93

Answers (2)

panos_vs_panos
panos_vs_panos

Reputation: 1

int size=values.length;
    int [] SortedbyValue=new int [size];
    for(int i=0;i<size;i++){
        SortedbyValue[values[i]]=i;
    }
    return SortedbyValue;

That's the answer i came up with...The above didn't help a lot.

Upvotes: 0

turbo
turbo

Reputation: 1897

Arrays.sort(values);

See the documentation for more information

If you want to copy the values to a new array and sort that array, there are a few ways you can do it, this should suffice:

int[] sortedValues = new int[values.length];
System.arraycopy( values, 0, sortedValues, 0, values.length );
Arrays.sort(sortedValues);

Upvotes: 4

Related Questions