0

I'm doing a school project and I got my ears caught in a 2d array trying to sort it.

So what I got is this:

String array[][]={  {"5", "22,2", "car payment", "visa", "21/04/2016},
                    {"3", "15,4", "shop", "cash", "16/02/2017},
                    {"1", "11,3", "gym", "visa", "10/01/2016}   };

What I need to do is list the array by the 2nd column (descending). So my listed array should be something like this:

{"1", "11,3", "gym", "visa", "10/01/2016}
{"3", "15,4", "shop", "cash", "16/02/2017}
{"5", "22,2", "car payment", "visa", "21/04/2016}

I tried something like this:

for (int i = 0; i < array.length; i++){
    for (int j = 0; j < array[i].length; j++) {
    if (Float.valueOf(array[i][1]) > Float.valueOf(array[i+1][1])) {
        temp = array[j+1];
        array[j+1] = array[j];
        array[j] = temp;
    }
  }
}

But seems to fail. Where am I doing wrong?

Thank you in advance!

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
ALx ALx
  • 111
  • 7

2 Answers2

2

You coded a strange mix between a bubble sort and a selection sort. The comparison should be between array[i][1] and array[j][1], not array[i][1] and array[i+1][1]:

if (Float.valueOf(array[i][1]) > Float.valueOf(array[j][1]))

This should work for floats with a dot decimal separator. If you need to parse floats with comma decimal separator, use this Q&A.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Refactor the 2d array for only a 1D array(you can save a pain in the neck...) , then use Arrays.sort and pass the own Comparator where you can compare the element2 of every row

Example:

public static void main(String[] args) {
    String[] array = { "\"5\", \"22,2\", \"car payment\", \"visa\", \"21/04/2016\"",
            "\"3\", \"15,4\", \"shop\", \"cash\", \"16/02/2017\"", "\"1\", \"11,3\", \"gym\", \"visa\", \"10/01/2016\"" };
    Arrays.sort(array, new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            return o1.split(",")[1].compareTo(o2.split(",")[1]);
        }
    });
    System.out.println(Arrays.toString(array));
}

this will sort the arrays by the "price" (I guess is the name of the field..)

Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • I would love to do that, but I get the 2d array by mixing 5 arrays into one. I get every one of the fields using an array (1 for input, 1 for price, 1 for category, 1 for payment type and 1 for date). And then I put all of them into this final String array. – ALx ALx May 08 '16 at 09:50