-2

I have a multidimensional array points[10][3] and I need to sort this based on the 3rd column. How do I go about this? There are other answer but I find them too advanced, can someone explain it to me like you would explain it to a 5 year old?

HindK
  • 143
  • 1
  • 1
  • 9
  • This link isn't helpful for you? http://stackoverflow.com/questions/4907683/sort-a-two-dimensional-array-based-on-one-column – Kallel Omar Mar 30 '15 at 13:03

2 Answers2

1

Have a look at this tutorial: https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html, especially section 'Comparators'.

Your data structure to be sorted is a two-dimensional array, which can also be seen as an array of arrays (an array that has arrays as elements):

// array containing 10 int[3]-arrays:
int[][] points = new int[10][3];

If you want to sort the 'outer' array, your sort algorithm needs to compare the elements of this array, so it must handle int[3] items, and we want to compare them by their last element (index = 2).

Java 7 (and below)

We can implement a Comparator, that is able to compare int arrays by their 3rd element:

Comparator<int[]> comparator = new Comparator<int[]> {
    public int compare(int[] a1, int[] a2) {
        return Integer.compare(a1[2], a2[2]);
    }
}

Now, we can use this comparator every time we want to sort an two-dimensional array like that:

Arrays.sort(points, comparator);

Java 8

Since Java 8 it is even simpler, you don't even need to implement a Comparator. Simply use lambda-expressions to define your comparison strategy:

Arrays.sort(points, Comparator.comparingInt(a -> a[2]));
isnot2bad
  • 24,105
  • 2
  • 29
  • 50
0

You just want to use some logical thiking.

Just assume it as a single dimnesional array and work on it.

//array with some temp values
        int points[][]={{5,5,16},{5,4,9},{6,7,10},{1,4,5},{1,5,2},{1,2,3},{2,1,10},{2,1,3},{5,5,2},{5,5,1}};

        //Just printing my array
        System.out.println("My Array :");
        for(int i=0;i<10;i++)
            System.out.println("{"+points[i][0]+","+points[i][1]+","+points[i][2]+"}");

        //using bubble sort
        for(int i=0;i<10;i++){
            for(int j=i+1;j<10;j++){
                //only checking the 3rd column
                if(points[i][2]>points[j][2])
                    swap(points[i],points[j]);
            }
        }

        System.out.println("After sorting :");
        for(int i=0;i<10;i++)
            System.out.println("{"+points[i][0]+","+points[i][1]+","+points[i][2]+"}");

I got the below output,

My Array :
{5,5,16}
{5,4,9}
{6,7,10}
{1,4,5}
{1,5,2}
{1,2,3}
{2,1,10}
{2,1,3}
{5,5,2}
{5,5,1}
After sorting :
{5,5,1}
{5,5,2}
{1,5,2}
{1,2,3}
{2,1,3}
{1,4,5}
{5,4,9}
{2,1,10}
{6,7,10}
{5,5,16}
Praveen
  • 1,791
  • 3
  • 20
  • 33