Leonid
Leonid

Reputation: 23460

Indexes mapping from sorted to original array

What is an easy way in Java to sort the array of elements maintaining information about indexes where the elements were stored in the original array? Is there a built-in function?

There are few ways I can think of, but none of them is trivial.

  1. Implement sort function yourself and return an array of indexes to the original array together with the sorted array.
  2. Wrap the elements into a class and store indexes of the original array inside this class, avoiding your sort function.

The reason I need it, is to rearrange the rows in the matrix, when the order of rearrangement is specified by values in the vector. Values in the vector should be in increasing order, and rows in the matrix should be rearranged accordingly.

Upvotes: 1

Views: 603

Answers (3)

Alberto Gutierrez
Alberto Gutierrez

Reputation: 1588

IMHO you would be better off creating your own design, maybe create a class called MyDataSorter with a method sort (yourArray) which returns a sorted List of your custom class which could also take generics... something like

List<OriginalOrderKeeper<MyDataType>> sort (MyDataType [] array)

Upvotes: 1

mtsz
mtsz

Reputation: 2855

Assume you could reorder the rows in the matrix directly, you would not need an index.

You can try sorting them using Arrays.sort(Object[] a, Comparator c) using a special comparator:

public class RowComparator implements Comparator<double[]> {

    public final int columnIndex;

    @Override
    public int compare(double[] row1, double[] row2) {
        return Double.compare(row1[columnIndex], row2[columnIndex]);
    }

    public RowComparator(int columnIndex) {
        super();
        this.columnIndex = columnIndex;
    }

    }

You initialize the comparator with the column index relevant for the comparison.

EDIT: Rows and columns got mixed up a bit. I assume a double[rows][columns] array.

Upvotes: 0

quaylar
quaylar

Reputation: 2635

Why not iterating once over the original array before sorting and storing the indexes in a Map<Object, Integer>?

Upvotes: 1

Related Questions