Dezido
Dezido

Reputation: 3

Sort a 2d array by the length of subarrays

I want to complete the following task:

You get an array of arrays. If you sort the arrays by their length, you will see, that their length-values are consecutive. But one array is missing! You have to write a method, that return the length of the missing array.

public static int getLengthOfMissingArray(Object[][] arrayOfArrays) {
    if (arrayOfArrays.length == 0) { //array empty
        return 0;
    }
    for (int i = 0; i < arrayOfArrays.length; i++) {
        //array in the array empty
        if (arrayOfArrays[i].length == 0) {
            return 0;
        }
        if (arrayOfArrays[i].length != arrayOfArrays[i + 1].length - 1) {
            return arrayOfArrays[i].length + 1;
        }
    }
    return 0;
}

This works for sorted arrays. So I just need a way to order them by their length.

Is there away to sort a 2D array by the (ascending) length of its subarrays?

For example: [[1,2], [1,5,7],[4]] -> [[4], [1,2], [1,5,7]]

Arrays.sort(arr) doesn't work and I get:

Ljava.lang.Object; cannot be cast to java.lang.Comparable

Upvotes: 0

Views: 397

Answers (2)

Programmer
Programmer

Reputation: 813

Use this method:

public static int[][] sort(int[][] arr) {
    for (int i = 0; i < arr.length; i++) {
        for (int j = i + 1; j < arr.length; j++) {
            if (arr[j].length < arr[i].length) {
                // If the length of the array in j less than the
                // length of the array in i, replace between them
                int[] temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return arr;
}

Upvotes: 1

user14940971
user14940971

Reputation:

You can use Arrays.sort(T[],Comparator) method:

Object[][] arr = {{1, 2}, {1, 5, 7}, {4}};

Arrays.sort(arr, Comparator.comparing(subArr -> subArr.length));

System.out.println(Arrays.deepToString(arr));
// [[4], [1, 2], [1, 5, 7]]

See also: Sort a 2d array by the first column, and then by the second one

Upvotes: 0

Related Questions