Klausos Klausos
Klausos Klausos

Reputation: 16050

How to sort an array by entry indexes?

I need to sort INDEXES of an array that contains double values. The sorting should be made in ascending order. I do this in the following way (see below). It works fine if an array contains integer values, but it stops working with double values. Why? Please notice that I am sorting the Indexes, not the values of an array.

The result should be [1,0], which refers to [893.05,1129.25].

double[] times = new double[2];

times[0] = 1129.25;
times[1] = 893.05;

ArrayIndexComparator comparator = new ArrayIndexComparator(times,0);
Integer[] sortedTimes = comparator.createIndexArray();
Arrays.sort(sortedTimes, comparator);

public class ArrayIndexComparator implements Comparator<Integer>
{
    private double[] array;
    private int sort;

    public ArrayIndexComparator(double[] array, int sort)
    {
        this.array = array;
        this.sort = sort;
    }

    public Integer[] createIndexArray()
    {
        Integer[] indexes = new Integer[array.length];
        for (int i = 0; i < array.length; i++)
        {
            indexes[i] = i;
        }
        return indexes;
    }

    @Override
    public int compare(Integer index1, Integer index2)
    {
        if (sort == 0)
            return Double.compare(array[index2],array[index1]); // descending order ...2,1,0
        else
            return Double.compare(array[index1],array[index2]); // ascending order 0,1,2,...
    }
}

Upvotes: 0

Views: 93

Answers (3)

vinayknl
vinayknl

Reputation: 1252

 ArrayIndexComparator comparator = new ArrayIndexComparator(times,1);

Using above ( passing 1 to instruct to sort ascending) , i am getting proper values in ascending order.

Test Code

    for(Integer op : sortedTimes)
    {
        System.out.println(times[op]);
    }

Output

893.05
1129.25

Upvotes: 0

tudoricc
tudoricc

Reputation: 729

I didn;t fully understand what you said but I got the result you wanted only modifying the compare function

    @Override
    public int compare(Integer index1, Integer index2)
    {

        if (index1<index2){
            return 1;
        }
        else if (index1>index2){
            return -1;
        }
        else{
            return 0;
        }
     }

Upvotes: 0

M A
M A

Reputation: 72844

In the compare method of your custom comparator, you are sorting in descending order since you have the sort field set to 0 in the call to your constructor.

Just replace the 0 with any other number in ArrayIndexComparator comparator = new ArrayIndexComparator(times,0);

e.g. ArrayIndexComparator comparator = new ArrayIndexComparator(times,1);

Upvotes: 1

Related Questions