Pzet
Pzet

Reputation: 490

Sorting a two-dimensional array doesn't sort in the right order

I'm trying to sort a two-dimensional array based on the second column, here is the array:

[1.1, 60.0]
[1.2, 66.66]
[1.3, -1.0]
[1.4, 50.0]
[1.5, 100.0]
[2.1, -1.0]
[2.2, -1.0]
[2.3, -1.0]

I looked into sorting mutli-dimensional arrays and created the following code:

    private void sortKnowledgeScores(double[][] knowledgescores){
    Arrays.sort(knowledgescores, new Comparator<double[]>() {
        @Override
        public int compare(double[] o1, double[] o2) {
            double itemOne = o1[1];
            double itemTwo = o2[1];
            // sort on item id
            if(itemOne < itemTwo){
                return (int) itemOne;
            }
            return (int) itemIdTwo;
        }

This rearranges the array to this:

[2.3, -1.0]
[2.2, -1.0]
[2.1, -1.0]
[1.3, -1.0]
[1.1, 60.0]
[1.2, 66.66]
[1.4, 50.0]
[1.5, 100.0]

Which is correct for the first three values however it puts 50 below 60 and 60.66. How can I adjust my sortKnowledgeScores function to sort my array based on the first column in ascending order?

Upvotes: 0

Views: 93

Answers (3)

Felix
Felix

Reputation: 2386

First of all, you're using the wrong index. The first element in an array is at index 0

You can use the Comparator-Factory Comparator.comparingDouble:

Comparator.comparingDouble(array -> array[0])
Arrays.sort(knowledgescores, Comparator.comparingDouble(array -> array[0]))

Upvotes: 2

dWinder
dWinder

Reputation: 11642

Comparator should return 1,0,-1 (as bigger, equel, less).

Generally, if the compare function return positive result the first element is bigger, 0 they equal and negative result mean the second obj is bigger.

You returning the values and not the compare result.

You can look at this doc

You need to change your code to:

public int compare(double[] o1, double[] o2) {
        return (int) o1[1] - o2[1];
 }

As @Mick point out - notice that index you using: index 0 is for the first column and index 1 is for the second

Upvotes: 3

Mick
Mick

Reputation: 973

You compare the elements with index "1". This translates to the second column. You should use index "0" if sorting should consider the first column.

Plus - as already mentioned - the compare method works like this:

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

Upvotes: 0

Related Questions